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

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

Mary-Kate Olsen
Release: 2024-12-14 09:30:11
Original
1003 people have browsed it

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

Inserting an Element After Another in JavaScript Without External Libraries

In the realm of JavaScript, programmers often seek to manipulate elements within the DOM. While jQuery and other libraries simplify such tasks, it's possible to achieve element insertion without relying on external dependencies.

Question:

How can an element be inserted after another element in JavaScript without the assistance of libraries like jQuery?

Answer:

To insert an element after an existing node, JavaScript provides the insertBefore() method. However, unlike insertBefore()'s primary purpose of inserting before a reference node, we can leverage it to achieve our goal.

The following snippet demonstrates how:

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Copy after login

where:

  • referenceNode represents the element after which you want to insert the new element
  • parentNode retrieves the parent element of the reference node
  • nextSibling refers to the element immediately after the reference node. If the reference node is the last child, nextSibling will be null, and insertBefore() will handle this case by appending to the end of the list.

Example Function:

A concise function can be created to encapsulate this operation:

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

Testing the Function:

To validate our code, we can utilize the following snippet:

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

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

This code will insert a test element after the

element with the id "foo".

The above is the detailed content of How to Insert an Element After Another in JavaScript Without Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template