Sling Academy
Home/TypeScript/TypeScript element.insertAdjacentText() method (practical examples)

TypeScript element.insertAdjacentText() method (practical examples)

Last updated: February 14, 2024

Introduction

TypeScript enhances JavaScript by adding types and providing tools for better code structuring and debugging. When working with TypeScript in the DOM, methods like element.insertAdjacentText() become powerful tools for dynamic content manipulation. This article explores the insertAdjacentText() method through practical examples, illustrating how it can enhance your TypeScript applications.

Examples

The element.insertAdjacentText() method allows you to insert text into a specified position relative to the element. It accepts two parameters: a position string and the text content. The position string can be one of four values:

  • "beforebegin": Before the element itself.
  • "afterbegin": Just inside the element, before its first child.
  • "beforeend": Just inside the element, after its last child.
  • "afterend": After the element itself.

Let’s delve into practical examples that demonstrate how to use insertAdjacentText() in various scenarios.

Example 1: Simple Text Insertion

Consider an HTML page with a div element:

<div id="exampleDiv">Hello,</div>

In TypeScript:

const div = document.getElementById('exampleDiv');
if (div) {
    div.insertAdjacentText('beforeend', ' World!');
}

This simple example appends ‘ World!’ to ‘Hello,’, resulting in ‘Hello, World!’ displayed within the div.

Example 2: Inserting Text with Control Structures

Now, imagine you want to use control structures to conditionally insert text. For instance, adding a greeting based on the time of day:

// Assume we have the same div from Example 1.
const greet = () => {
    const hour = new Date().getHours();
    const greeting = hour < 12 ? 'Good morning' : 'Good afternoon';
    div?.insertAdjacentText('afterbegin', greeting + ', ');
};
greet();

Depending on the time, this inserts either ‘Good morning, ‘ or ‘Good afternoon, ‘ at the beginning of our div.

Example 3: Using insertAdjacentText() in Loops and Functions

For a more complex example, let’s use insertAdjacentText() within a loop to dynamically create a list:

// Assume a <ul> element with id 'list'.
const items = ['Apples', 'Oranges', 'Bananas'];
const list = document.getElementById('list');
items.forEach(item => {
    const li = document.createElement('li');
    list?.appendChild(li);
    li.insertAdjacentText('beforeend', item);
});

This will iterate over the items array, adding each item as a list element’s text.

Advanced Usage: Manipulating Text Based on Events

In a more advanced scenario, we might want to manipulate text based on user interactions. For example, changing a button’s text when it’s clicked:

// HTML: <button id="changeTextButton">Click me!</button>
const button = document.getElementById('changeTextButton');
button?.addEventListener('click', () => {
    button.textContent = 'Clicked!';
    // Using insertAdjacentText() to add some additional info
    button.insertAdjacentText('afterend', ' You have clicked the button.');
});

This changes the button’s text to ‘Clicked!’ and appends a message just after the button upon being clicked.

Conclusion

The element.insertAdjacentText() method is a versatile tool in TypeScript for manipulating text nodes relative to elements in the DOM. From inserting simple greetings to reacting based on user interactions, it offers a straightforward yet powerful way to enhance web applications. By incorporating insertAdjacentText() into your projects, you can dynamically manage document content, providing an improved user experience.

Next Article: TypeScript: Adding Multiple Classes to An Element

Previous Article: TypeScript – element.innerHTML and element.textContent

Series: TypeScript: Intermediate & Advanced Tutorials

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)