In this section, we will learn what the Element insertAdjacentElement() method is and how to use it in JavaScript.
What is Element insertAdjacentElement() Method in JavaScript?
The JavaScript Element insertAdjacentElement() method is used to insert a new element to a document, but relative to the element that invoked this method.
Element insertAdjacentElement() Method Syntax:
element.insertAdjacentElement(position, element);
Element insertAdjacentElement() Method Parameter
The method takes two arguments:
– The first argument is the position where we want to insert the new element.
There are 4 possible values for this first argument:
‘beforebegin‘: Using this value means the new element should be added as the previous sibling of the element that invoked this method.
‘afterbegin‘: Using this value means the new element should be added as the first child of the element that invoked this method.
‘beforeend‘: Using this value means the new element should be added as the last child of the element that invoked this method.
‘afterend‘: Using this value means the new element 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 element that we want to add to the document.
Element insertAdjacentElement() Method Return Value
The return value of this method is a reference to the new element that was inserted into the document or null if the operation failed.
Example: using insertAdjacentElement() method in JavaScript
See the Pen using insertAdjacentElement() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.