There's insertBefore()
in JavaScript, but how can I insert an element after another element without using jQuery or another library?
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With