2018 年解决方案(不良做法,转至 2020 年)
我知道这个问题很古老,但对于任何未来的用户,这里有一个修改过的原型。这只是不存在的 .insertAfter 函数的 polyfill。这个原型直接将函数HTMLElement.insertAfter(element);添加到HTMLElement Prototype中:
// Parent
const el = document.body;
// New Element
const newEl = document.createElement("div");
// Custom Method
Element.prototype.insertAfter = function(new) {
this.parentNode.insertBefore(new, this.nextSibling);
}
// Insert Before Element
el.insertBefore(newEl)
// Insert After Element
el.insertAfter(newEl);
// Just remember you cant use .insertAfter() or .insertBefore()
// after either is already called.
// You cant place one element in two places at once.
2019 解决方案(丑陋/过时,转到 2020)
不要使用原型(如 2018 解决方案)。覆盖原型既危险又低质量。如果您需要新方法,请改用函数覆盖。
如果您想要商业项目的安全功能,只需使用默认功能。它不那么漂亮,但它有效:
// Parent
const el = document.body;
// New Element
const newEl = document.createElement("div");
// Function You Need
function insertAfter(el0, el1) {
el0.parentNode.insertBefore(el1, el0.nextSibling);
}
// Insert Before Element
el.insertBefore(newEl);
// Insert After Element
insertAfter(el, newEl);
// Just remember you cant use insertAfter() or .insertBefore()
// after either is already called.
// You cant place one element in two places at once.
2020 解决方案 - ChildNode
ChildNode 的当前 Web 标准:MDN Docs - ChildNode
它目前符合生活标准,可以安全使用。
对于不支持的浏览器(例如 IE),使用这个 Polyfill:https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js
当我说它们是不好的做法时,我意识到 polyfill 使用了 Proto Overrides。它们是,特别是当它们被盲目使用时,就像我的第一个解决方案一样。但是,MDN 文档中的 polyfill 使用了一种初始化和执行形式,与仅覆盖原型相比,它更加可靠和安全。
如何使用子节点:
// Parent
const el = document.body;
// New Element
const newEl = document.createElement("div");
// Insert Before Element
el.before(newEl);
// Insert After Element
el.after(newEl);
// Just remember you cant use .after() or .before()
// after either is already called.
// You cant place one element in two places at once.
// Another feature of ChildNode is the .remove() method,
// which deletes the element from the DOM
el.remove();
newEl.remove();