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
Release: 2024-12-09 10:52:07
Original
1069 people have browsed it

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);
Copy after login

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);
}
Copy after login

You can then use this function like so:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template