JavaScript insertAdjacentText() Method Tutorial

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

What is Element insertAdjacentText() Method in JavaScript?

The JavaScript Element insertAdjacentText() method is used to insert a new text-node to a document, but relative to the element that invoked this method.

Element insertAdjacentText() Method Syntax:

element.insertAdjacentText(position, node);

Element insertAdjacentText() 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 insertAdjacentText() Method Return Value

The return value of this method is undefined.

Example: using insertAdjacentText() method in JavaScript

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

Leave a Reply