What is insertAdjacentHTML() ? How to use it?

featured Image

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

Related Posts

git commands with example

Top 40 Git commands with Examples

GitHub has become an essential tool for developers to manage, store, and collaborate with other developers on software projects. With its simple powerful git-based version control system, GitHub allows users…

Read more
Check GitHub Account in the Terminal

Check GitHub Account in the Terminal

GitHub is an integral tool for developers to store, manage, and collaborate on software projects with other developers. And as we work more and more in the command line it…

Read more
featured Image

How to make list of objects in Netlify CMS using list and object Widget

Here in this Netlify CMS tutorial we will how easily we can make a list of objects using list and object widgets. This will allow us to add multiple objects…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *