![]() |
The Manipulation of DOM (Document Object Model) is a fundamental task in web development. One common requirement is to insert a new element after an existing one. While libraries like jQuery make this task easy it’s useful to know how to accomplish it with pure JavaScript. This article will guide you through the steps to insert an element after another element using native JavaScript methods. Inserting an Element After Another ElementTo insert an element after another element we can use the insertBefore method in combination with the nextSibling property. The insertBefore method inserts a node before a specified child node and the nextSibling property returns the node immediately followed by the specified node. Step To Insert An Element After AnotherStep 1: Create the New ElementFirst, create a new element that we want to insert. We can use the createElement method to create a new element and the createTextNode method to create a text node if needed. let newElement = document.createElement('div'); Step 2: Select the Reference ElementNext, select the existing element after which we want to insert the new element. We can use methods like getElementById getElementsByClassName, getElementsByTagName or querySelector to select the reference element. let referenceElement = document.getElementById('referenceElement'); Step 3: Insert the New ElementTo insert the new element after the reference element use insertBefore method with the nextSibling of the reference element. If the reference element is the last child, nextSibling will be null and insertBefore will behave like appendChild. referenceElement.parentNode.insertBefore(newElement, referenceElement.nextSibling); ExampleHere is a complete example demonstrating how to insert the new element after an existing one:
Output![]() How to Insert an Element After Another in JavaScript Without Using a Library? |
Reffered: https://www.geeksforgeeks.org
HTML |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |