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:
- beforebegin : before the element. (valid if the element has a parent element).
- afterbegin: inside the element and before the first child of the element.
- beforeend: after the last child of the element and inside the element
- 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:
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: