Element.prepend()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
语法
Element.prepend((Node or DOMString)... nodes);
参数
返回值
undefined
.
异常
HierarchyRequestError
:节点不能插入当前层级内。
示例
Prepending an element
js
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
js
var parent = document.createElement("div");
parent.append("Some text");
parent.prepend("Headline: ");
console.log(parent.textContent); // "Headline: Some text"
Appending an element and text
js
var parent = document.createElement("div");
var p = document.createElement("p");
parent.prepend("Some text", p);
console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
Element.prepend()
is unscopable
prepend()
不能在 with 语句内使用,详情参考 Symbol.unscopables
。
js
var parent = document.createElement("div");
with (parent) {
prepend("foo");
}
// ReferenceError: prepend is not defined
规范
Specification |
---|
DOM Standard # ref-for-dom-parentnode-prepend① |
浏览器兼容性
BCD tables only load in the browser