JavaScript insertAdjacentHTML() Method Tutorial

In this section, we will learn what the Element insertAdjacentHTML() method is and how to use it in JavaScript.

What is Element insertAdjacentHTML() Method in JavaScript?

The JavaScript Element insertAdjacentHTML() method is used to insert a new text-node as an HTML element into a document relative to the element that invoked this method.

Note that we are saying “a text-node as an HTML element”! That means browsers interpret the content of the text and render those keywords that are special in HTML, CSS, etc.

For example, if the text is `<h1> This is a header</h1>` then browsers will interpret the opening and closing tags of the <h1> element and render the content as part of the h1 header.

Note: The interpretation that occurs in this method is like the `innerHTML` property.

Element insertAdjacentHTML() Method Syntax:

element.insertAdjacentHTML(position, text-node);

Element insertAdjacentHTML() Method Parameter

The method takes two arguments:

– The first argument is the position where we want to insert the text-node.

There are 4 possible values for this first argument:

beforebegin‘: Using this value means the text-node should be added as the previous sibling of the element that invoked this method.

afterbegin‘: Using this value means the text-node should be added as the first child of the element that invoked this method.

beforeend‘: Using this value means the text-node should be added as the last child of the element that invoked this method.

afterend‘: Using this value means the text-node should be added as the next sibling of the element that invoked this method.

– The second argument of the method is a reference to the text-node that we want to add to the document.

Element insertAdjacentHTML() Method Return Value

The method does not return a value.

Example: using insertAdjacentHTML() method in JavaScript

See the Pen using insertAdjacentHTML() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies