What is insertAdjacentHTML() ? How to use it?
Tutorial on Javascript insertAdjacentHTML() method and how can we use it to insert html elements to specific position in our HTML page.
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:

Related Posts
How to change the color of <hr> tag using CSS
Here we will learn how to change the color or the background color of HR element in out html using css style.
Horizontal scrolling div with arrows using HTML and CSS
Tutorial on how to make horizontal scrolling div with arrows using html and css and for smooth scrolling we will use scrollBy() function in Javascript.
How to make a placeholder for select box in HTML
Short tutorial on how we can add placeholder text for the select option element for dropdown in Html without CSS.
How do I wrap text in <code> tag HTML
This article is on how to wrap text in code tag in html. We will use white-pace, word-break and word-wrap CSS property to get our result.
