The following code shows an Example of insertAdjacentText() Method in JavaScript.


Illustrating an Example of insertAdjacentText() Method in JavaScript

Like insertAdjacentHTML() method, this method also inserts the given text at a specific position. However, this method adds a text rather than an HTML element.

  <title>insertAdjacentText Method Demo</title>
     function f1()
        var v1=document.getElementById("d1"); 
        v1.insertAdjacentText('beforebegin','Sample Text 1');
      function f2()
        var v1=document.getElementById("d1"); 
        v1.insertAdjacentText('afterbegin','Sample Text 2');
      function f3()
        var v1=document.getElementById("d1"); 
        v1.insertAdjacentText('beforeend','Sample Text 3');
      function f4()
        var v1=document.getElementById("d1"); 
        v1.insertAdjacentText('afterend','Sample Text 4');
       border: 4px solid #33ff99;
       border-radius: 10px;
       background-color: #5566aa;
       color: #aaffff;
       font-size: 20px;
       text-align: center;
       padding: 10px;
		margin: 50px;
       background-color: #ddeeff;
       color: #ff5566;
       font-size: 25px;
       text-align: left;
       padding: 5px;
       width: 800px;
  <div id="d1" class="c2"><br/><br/>
     Example of insertAdjacentText() Method<br/>
     <button id="b1" class="c1" onclick="f1()">Add Text Before Begin</button>
     <button id="b2" class="c1" onclick="f2()">Add Text After Begin</button>
     <button id="b3" class="c1" onclick="f3()">Add Text Before End</button>
     <button id="b4" class="c1" onclick="f4()">Add Text After End</button>


The Output of the Example of insertAdjacentText() Method in JavaScript
The Output of the Example of insertAdjacentText() Method in JavaScript

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Creating User-Defined Functions in javaScript

Popup Boxes in JavaScript