ParentNode.prepend
方法可以在父节点的第一个子节点之前插入一系列Node
对象或者DOMString
对象。DOMString
会被当作Text
节点对待(也就是说插入的不是HTML代码)。
语法
ParentNode.prepend((Node or DOMString)... nodes);
参数
返回值
undefined
.
错误
HierarchyRequestError
:节点不能插入当前层级内。
例子
Prepending an element
var parent = document.createElement("div");
var p = document.createElement("p");
var span = document.createElement("span");
parent.append(p);
parent.prepend(span);
console.log(parent.childNodes); // NodeList [ <span>, <p> ]
Prepending text
var parent = document.createElement("div");
parent.append("Some text");
parent.prepend("Headline: ");
console.log(parent.textContent); // "Headline: Some text"
Appending an element and text
var parent = document.createElement("div");
var p = document.createElement("p");
parent.prepend("Some text", p);
console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
ParentNode.prepend() is unscopable
prepend()不能在with语句内使用,详情参考
Symbol.unscopables
。
var parent = document.createElement("div");
with(parent) {
prepend("foo");
}
// ReferenceError: prepend is not defined
Polyfill
使用下面的代码在IE9或更高版本中模拟prepend()
方法:
// from: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/prepend()/prepend().md
(function (arr) {
arr.forEach(function (item) {
item.prepend = item.prepend || function () {
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.insertBefore(docFrag, this.firstChild);
};
});
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
说明
Specification | Status | Comment |
---|---|---|
DOM ParentNode.prepend() |
Living Standard | Initial definition. |
兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.