Home >Web Front-end >JS Tutorial >How to Insert an Element After Another in JavaScript?

How to Insert an Element After Another in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 03:44:13444browse

How to Insert an Element After Another in JavaScript?

Inserting an Element After Another in JavaScript

While JavaScript provides the insertBefore() method to insert an element before another, there is no built-in method for inserting an element after another. To achieve this, we can utilize the following custom technique:

Solution:

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

Explanation:

  • referenceNode: The element you want to insert the new element after.
  • newNode: The new element to be inserted.
  • parentNode: The parent element of the reference node.
  • nextSibling: The node following the reference node (or null if it's the last child).

insertBefore() takes two arguments: the new node to insert and the node before which the new node should be placed. By passing in referenceNode.nextSibling, we ensure that the new node is inserted after the reference node.

Example Function:

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Usage:

var el = document.createElement("span");
el.innerHTML = "test";
var div = document.getElementById("foo");
insertAfter(div, el);

This will insert a span element with the text "test" after the div element with the id "foo".

The above is the detailed content of How to Insert an Element After Another in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn