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

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?

 

回答1

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>

 

 

回答2

Though insertBefore() is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use:

The insertAdjacentElement() as refElem.insertAdjacentElement(position, newElem) lets you reference any element, and insert the to-be moved element exactly where you want (position can be one of: 'beforebegin', 'afterbegin', 'beforeend', 'afterend') as shown below:

// refElem.insertAdjacentElement('beforebegin', myElem); 
<p id="refElem">
    // refElem.insertAdjacentElement('afterbegin', myElem);
    ... content ...
    // refElem.insertAdjacentElement('beforeend', myElem);
</p>
// refElem.insertAdjacentElement('afterend', myElem); 

Others to consider for similar use cases: insertAdjacentHTML() and insertAdjacentText()

References:

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-04-26 Customising the browse for folder dialog to show the path
2019-04-26 正则匹配IP
点击右上角即可分享
微信分享提示