使用insertBefore(),並將元素加入至父層的第一個元素之前
// Create a new element
var newNode = document.createElement('div');
// Get the parent node
var parentNode = document.querySelector('#some-element');
// Insert the new node before the reference node
parentNode.insertBefore(newNode, parentNode.firstChild);
prepend()
prepend()為ES6的新方法
// Create a new element
var newNode = document.createElement('div');
// Get the parent node
var parentNode = document.querySelector('#some-element');
// Insert the new node before the reference node
parentNode.prepend(newNode);
prepend()支援新版的Chrome、Firefox、Opera,不支援IE與Edge
以下為IE7以上的polyfill
var _mutation = (function () {
function isNode(object) {
// DOM, Level2
if (typeof Node === 'function') {
return object instanceof Node;
}
// Older browsers, check if it looks like a Node instance)
return object &&
typeof object === "object" &&
object.nodeName &&
object.nodeType >= 1 &&
object.nodeType <= 12;
}
// http://dom.spec.whatwg.org/#mutation-method-macro
return function mutation(nodes) {
if (nodes.length === 1) {
return isNode(nodes[0]) ? nodes[0] : document.createTextNode(nodes[0] + '');
}
var fragment = document.createDocumentFragment();
for (var i = 0; i < nodes.length; i++) {
fragment.appendChild(isNode(nodes[i]) ? nodes[i] : document.createTextNode(nodes[i] + ''));
}
return fragment;
};
}());
Document.prototype.prepend = Element.prototype.prepend = function prepend() {
this.insertBefore(_mutation(arguments), this.firstChild);
};
REFERENCE: Go Make Things
留言列表