close

使用insertBefore(),並在node後呼叫下一個節點元素

// Create a new element
var newNode = document.createElement('div');

// Get the reference node
var referenceNode = document.querySelector('#some-element');

// Insert the new node before the reference node
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);


after()
如今,ES6帶了新方法after(),

// Create a new element
var newNode = document.createElement('div');

// Get the reference node
var referenceNode = document.querySelector('#some-element');

// Insert the new node before the reference node
referenceNode.after(newNode);

與before()一樣不支援IE,需使用polyfill支援至IE9

//from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('after')) {
return;
}
Object.defineProperty(item, 'after', {
configurable: true,
enumerable: true,
writable: true,
value: function after() {
var argArr = Array.prototype.slice.call(arguments),
docFrag = document.createDocumentFragment();

argArr.forEach(function (argItem) {
var isNode = argItem instanceof Node;
docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
});

this.parentNode.insertBefore(docFrag, this.nextSibling);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);


REFERENCE: Go Make Things

arrow
arrow
    創作者介紹
    創作者 浣熊 的頭像
    浣熊

    前端生涯

    浣熊 發表在 痞客邦 留言(0) 人氣()