Insert a specified element in a specified position in JavaScript?


Javascript has provided "insertAdjacentElement()" to insert an already existing element in a specified position. If there are multiple elements with the same name then use indexes to access them as we access the array elements. 

syntax

node.insertAdjacentHTML(position, element);

Example-1

In the following example, there are actually 3 elements in parallel span1, span2, and header. Using the method insertAdjacentElement() we have placed the element span1 below the header as shown in the output.

Live Demo

<html>
<body>
<span>My span1</span>
<span>My span2</span>
<h2 id="H2">My Header</h2>
<script>
   var s = document.getElementsByTagName("span")[0];
   var h = document.getElementById("H2");
   h.insertAdjacentElement("afterend", s);
</script>
</body>
</html>

Output

My span2
My Header
My span1


Example-2

In the following example, there are actually 3 elements in parallel span1, span2, and header. Using the method insertAdjacentElement() we have placed the element span2 below the header as shown in the output. if there are multiple elements access the elements like an array, accessing through the indexes.

Live Demo

<html>
<body>
<span>My span1</span>
<span>My span2</span>
<h2 id="H2">My Header</h2>
<script>
   var s = document.getElementsByTagName("span")[1];
   var h = document.getElementById("H2");
   h.insertAdjacentElement("afterend", s);
</script>
</body>
</html>

Output

My span1
My Header
My span2
raja
Published on 09-Aug-2019 08:55:45
Advertisements