appendChild()
appendChild()將元素添加到一組元素的結尾
// Create a new element
var newNode = document.createElement('div');
// Get the parent node
var parentNode = document.querySelector('#some-element');
// Insert the new node after the last element in the parent node
parentNode.appendChild(newNode);
append()
ES6的新方法
// Create a new element
var newNode = document.createElement('div');
// Get the parent node
var parentNode = document.querySelector('#some-element');
// Insert the new node after the last element in the parent node
parentNode.append(newNode);
append()支援新版的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.append = Element.prototype.append = function append() {
this.appendChild(_mutation(arguments));
};
REFERENCE: Go Make Things
留言列表