This guide explains the objective, working, and usage of the “insertAdjacent HTML()” method in JavaScript.
What Does the “insertAdjacentHTML()” Method do in JavaScript?
The “insertAdjacentHTML()” method assists the users to inserts the HTML code into a particular position.
Syntax
In the above syntax:
- element: It represents the associated HTML element.
- position: It specifies the four relative positions of an HTML element, as follows:
- beforebegin: Before the HTML element.
- afterbegin: Right after the first child of the HTML element.
- afterend: At the end of the HTML element.
- beforeend: After the last child of the HTML element.
- html: It refers to the inserted HTML element.
Example: Applying the “insertAdjacentHTML()” to Insert Elements At Relative Positions
This example applies the discussed method to insert the elements at the four specific positions with respect to a particular element i.e., “<ul>”.
HTML Code
First, go through the following HTML code:
In the above code snippet:
- Firstly, create a subheading using the “<h2>” tag.
- Next, utilize the “<ul>” tag to create the unordered list with an assigned id “demo”.
- The “<li>“ tag adds up the stated item in the list.
JavaScript Code
Now, move on to the JavaScript code block:
let list = document.getElementById("demo");
list.insertAdjacentHTML('beforebegin', '<h2>Operating Systems</h2>');
list.insertAdjacentHTML('afterbegin', '<li>Windows</li>');
list.insertAdjacentHTML('beforeend', '<li>Mac OS</li>');
list.insertAdjacentHTML('afterend', '<p>That’s all</p>');
</script>
In the above code snippet:
- Declare a variable “list” that utilizes the “getElementById()” method to fetch the included “<ul>” element comprising the id “demo”.
- Next, apply the “insertAdjacentHTML()” method to insert the subheading via the “<h2>” tag before the start of the “<ul>” i.e., at the “beforebegin” position.
- After that, insert the item via the “<li>” tag after the start of the “<ul>” tag i.e., at the “afterbegin” position.
- Again, use the ”<li>“ tag to add a list item before the end of the “<ul>” tag i.e., at the “beforeend” position.
- Lastly, insert a paragraph with the help of the “<p>” tag after the end of the “<ul>” tag at the “afterend” position.
Output
As seen, all the defined HTML elements are inserted at their assigned position with the help of the “insertAdjacentHTML()” method.
Conclusion
JavaScript provides a well-reputed built-in “insertAdjacentHTML()” method for appending the HTML element at four different positions. It instructs the browser to adjust the stated HTML element at “beforebegin”, “beforeend”, “afterbegin”, and the “afterend” positions with respect to a particular element. This guide discussed the working and use of the “insertAdjacentHTML()” method in detail.