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对象或者DOMString对象。DOMString会被当作Text节点对待(也就是说插入的不是 HTML 代码)。

语法

Element.prepend((Node or DOMString)... nodes);

参数

nodes

要插入的一系列Node或者DOMString

返回值

undefined.

异常

示例

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

参见