Advertisement
  1. Code
  2. JavaScript

Inserting Text, HTML, or Elements at Adjacent Positions Using JavaScript

Scroll to top
Read Time: 5 min

There are many DOM manipulation tutorials on Envato Tuts+ that teach you how to do a variety of things such as finding the parents, children, or siblings of an element. We also have a tutorial that teaches you how to insert, replace, or remove child elements in JavaScript.

This tutorial will show you how to insert text, HTML, or elements at adjacent positions using JavaScript.

Inserting Text at Adjacent Positions

Let's begin with the insertion of text at adjacent positions. We can do this with the help of the insertAdjacentText() method. This method accepts two parameters.

The first parameter determines the position of the text node relative to the element. The parameter value must be a string, and it can have one of the following four values:

  1. beforebegin: This will insert the text node just before the element.
  2. afterbegin: This will insert the text node inside the element, before its first child.
  3. beforeend: This will insert the text node inside the element, after the last child.
  4. afterend: This will insert the text node just after the element.

The second parameter is also a string, which represents the actual text node value that you want to insert. Here is a simple code snippet that gets the text value from an input element and then places it at the specified positions:

1
let p_elem = document.querySelector("p.my-para");
2
let input_elem = document.querySelector("input");
3
let text_wrapper = document.querySelector("div.text-wrapper");
4
let c_node = document.querySelector("span.c-node");
5
6
c_node.textContent = text_wrapper.childNodes.length;
7
8
document.querySelector(".bb").addEventListener("click", () => {
9
  p_elem.insertAdjacentHTML('beforebegin', input_elem.value);
10
  c_node.textContent = text_wrapper.childNodes.length;
11
});
12
13
document.querySelector(".ab").addEventListener("click", () => {
14
  p_elem.insertAdjacentText('afterbegin', input_elem.value);
15
  c_node.textContent = text_wrapper.childNodes.length;
16
});

The following CodePen demo shows the insertion of text at adjacent positions in action.

One interesting thing to note here is that the total number of child nodes stays the same when the text is inserted using afterbegin and beforeend as position values. This is because that text is inserted inside an existing element or node.

On the other hand, the text added using the beforebegin and afterend position values results in an increase in the total number of child nodes. Each button press results in the creation of one new node instead of the text getting added to existing text nodes.

You can insert content at the beforebegin and afterend positions only if the calling element also has an element parent.

Inserting HTML at Adjacent Positions

You can use the insertAdjacentHTML() method if you want to insert some text as HTML or XML instead of plain text. The resulting nodes are inserted into the DOM tree at the specified positions.

The positions where you can insert the HTML are the same ones we discussed in the previous section: beforebegin, afterbegin, beforeend, and afterend.

One advantage of the insertAdjacentHTML() method is that it does not reparse the calling element, which makes it a lot faster than using innerHTML to update the HTML. Using insertAdjacentHTML() also prevents the corruption of any existing HTML inside the calling element.

Using this method to insert HTML into a page can be a security risk. Therefore, you have to be sure that the user input has been escaped and sanitized. It's possible for malicious users to inject harmful scripts into the web page if you are not careful.

While it's tempting to use insertAdjacentHTML() to insert both markup and plain text, you should consider using insertAdjacentText() if you plan to insert plain text. This is because insertAdjacentHTML() will spend some time parsing the passed string, while insertAdjacentText() will insert it as a raw string.

Consider the following example where the raw string is inserted at beforebegin, while the parsed <b> tag is inserted afterend.

1
let p_elem = document.querySelector("p.my-para");
2
3
p_elem.insertAdjacentText("beforebegin", "<b>Hello, Tyrion Lannister</b>");
4
p_elem.insertAdjacentHTML("afterend", "<b>Hello, Tyrion Lannister</b>");

You can see it in action in the following CodePen demo:

Insert an Element at Adjacent Positions

There is one more similar method, called insertAdjacentElement(), that you can use to insert a given element node at a specified position with respect to the calling element.

The value of the position parameter will be the same for this method as the previous two methods: beforebegin, afterbegin, beforeend, and afterend.

The return value of this method is the element that was inserted. It will return null if the insertion failed.

Here is a little code snippet that takes some text input from an input element and wraps it in span tags when inserting at the beforebegin position. The text is wrapped inside p tags when inserting at the afterbegin position.

1
let p_elem = document.querySelector("p.my-para");
2
let input_elem = document.querySelector("input");
3
let p_count = document.querySelector("div.text-wrapper").getElementsByTagName("p");
4
let c_node = document.querySelector("span.c-node");
5
6
c_node.textContent = p_count.length;
7
8
document.querySelector(".bb").addEventListener("click", () => {
9
  let temp_para = document.createElement("p");
10
  temp_para.textContent = input_elem.value;
11
  p_elem.insertAdjacentElement('beforebegin', temp_para);
12
  
13
  c_node.textContent = p_count.length;
14
});
15
16
document.querySelector(".ab").addEventListener("click", () => {
17
  let temp_span = document.createElement("span");
18
  temp_span.textContent = input_elem.value;
19
  p_elem.insertAdjacentElement('afterbegin', temp_span);
20
  
21
  c_node.textContent = p_count.length;
22
});

You can see it in action in the following CodePen demo:

Final Thoughts

In this tutorial, we learned about three different methods that you can use to insert text, HTML, or elements at specified positions relative to the parent element. You should always use insertAdjacentText() to insert text strings for better performance. Similarly, insertAdjacentElement() is also usually faster when you want to insert an actual existing element into the DOM tree.

One advantage of using insertAdjacentHTML() is that you can simply pass it a string that it will parse to insert the appropriate nodes into the DOM. Using insertAdjacentHTML() is much simpler if you want to insert complicated markup.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.