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.


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="" />

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

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

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



Generate unordered list using insertAdjacentHTML()

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


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

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


list item with insertadjacenthtml() method

💾 Recommended Articles