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

Programmingempire

Illustrating an Example of insertAdjacentElement() Method in JavaScript

Basically, the following HTML document contains a button. Also, it has an event handler method for the click event called f1(). When the user clicks on the above button, the createElement() method creates a button element. While, the insertAdjacentElement() method inserts this button.

<html>
<head>
  <title>insertAdjacentElement Method Demo</title>
  <script>
     count=1;
     function f1()
     {
        var v1=document.getElementById("b7"); 
        var bt=document.createElement('button');
	bt.style.margin='10px';
	bt.innerText="Button "+count;
	count=count+1;
	
        v1.insertAdjacentElement('afterend',bt);
      }
  </script>
  <style>
    .c1{
       border: 4px solid #33ff99;
       border-radius: 10px;
       background-color: #5566aa;
       color: #aaffff;
       font-size: 20px;
       text-align: center;
       margin:5px;
       padding: 10px;
      }
    .a1{
		margin: 50px;
	}
    .c2{
       background-color: #ddeeff;
       color: #ff5566;
       font-size: 25px;
       text-align: left;
       margin:40px;
       padding: 5px;
       width: 800px;
      }
  </style>
</head>
<body>
  <div id="d1" class="c2"><br/><br/>
     Example of insertAdjacentElement() Method<br/>
     <br/><br/>
     <button id="b7" class="c1" onclick="f1()">Click to Add Another Button</button>
 </div>
</body>
</html>

Output

The Output of an Example of insertAdjacentElement() Method in JavaScript
The Output of an Example of insertAdjacentElement() 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

programmingempire