What is insertAdjacentHTML() ? How to use it?

In this article, we will learn about the JavaScript insertAdjacentHTML() method along with some examples of how to use it.

The insertAdjacentHTML() method parses any specific text into HTML and inserts it into the DOM tree at a specific position.

This method takes two parameters: the position and the text containing HTML.

Syntax:

insertAdjacentHTML(postion, text)

text: This is the string parsed as HTML to be inserted in the DOM tree.

postion : It represents the position relative to the element.

There are four possible positions:

  1. beforebegin : before the element. (valid if the element has a parent element).
  2. afterbegin: inside the element and before the first child of the element.
  3. beforeend: after the last child of the element and inside the element
  4. afterend: after the element (valid if it has a parent element)

Let’s see some examples using insertAdjacentHTML() using JavaScript.

Let’s say we have a < div > with class “parent” and inside the div, we have an image using < img > tag.

<div class="parent">
   <img src="img.jpeg" width="100%" alt="" srcset="" />
</div>

Now, we want to insert a heading inside the parent div and above the image.

<script>
  const parentDiv = document
      .querySelector(".parent")
      .insertAdjacentHTML("afterbegin", "<h1>This is a Image</h1>");
</script>

The position “afterbegin” have inserted the heading inside the parent div and above the image i.e the first child.

Output:

inseradjacenthtml javascript

Generate unordered list using insertAdjacentHTML()

You can also use the insertAdjacentHTML() to add < li > elements in an unordered list.

<ul>
   <li>one</li>
   <li>two</li>
   <li>three</li>     
</ul>

We will use the position “beforeend” to add <li> element after the last child element.

 const ul = document
        .querySelector("ul")
        .insertAdjacentHTML("beforeend", "<li>four</li>");

Output:

list item with insertadjacenthtml() method

Scroll to Top