📌  相关文章
📜  如何在不使用库的情况下在 JavaScript 中的另一个元素之后插入一个元素? - Javascript代码示例

📅  最后修改于: 2022-03-11 15:01:31.350000             🧑  作者: Mango

代码示例2
//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);
Hello