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

How to Insert an Element After Another in JavaScript Without Libraries?

DDD
DDDOriginal
2024-12-09 10:52:071032browse

How to Insert an Element After Another in JavaScript Without Libraries?

Inserting Elements After Others in JavaScript Without a Library

In JavaScript, the insertBefore() method exists for inserting an element before a specified reference node. However, what if you want to insert an element after another element without relying on jQuery or other libraries?

Answer

The following snippet is what you need:

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

Here's how it works:

  • referenceNode represents the node after which you want to insert the new node (newNode).
  • referenceNode.parentNode gets the parent node of the referenceNode.
  • referenceNode.nextSibling identifies the next sibling of the referenceNode. If the referenceNode is the last child, nextSibling will be null. This case is handled appropriately by insertBefore(), which appends to the end of the child list.

Example Code

To use this solution, you can define the following function:

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

You can then use this function like so:

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

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

The above is the detailed content of How to Insert an Element After Another in JavaScript Without Libraries?. 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