Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an element after another element in JavaScript without using a library?

There's insertBefore() in JavaScript, but how can I insert an element after another element without using jQuery or another library?

like image 951
Xah Lee Avatar asked Jan 25 '11 12:01

Xah Lee


People also ask

How do you add an element after another element?

First, select the ul element by its id ( menu ) using the getElementById() method. Second, create a new list item using the createElement() method. Third, use the insertAfter () method to insert a list item element after the last list item element.

How do you add an element before another element?

In vanilla JavaScript, you can use the insertBefore() method to insert an element before another HTML element in the DOM. This method adds an element, right before an existing element in the document.

What is the alternative for append in JavaScript?

replaceChildren() is a convenient alternative to innerHTML and append() append() appends nodes to the parent node. The contents that were inside the node before the append() invocation remain preserved.


1 Answers

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

Where referenceNode is the node you want to put newNode after. If referenceNode is the last child within its parent element, that's fine, because referenceNode.nextSibling will be null and insertBefore handles that case by adding to the end of the list.

So:

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

You can test it using 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);
<div id="foo">Hello</div>
like image 145
karim79 Avatar answered Sep 27 '22 23:09

karim79