ParentNode.prepend()

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

ParentNode.prepend 方法可以在父节点的第一个子节点之前插入一系列Node对象或者DOMString对象。DOMString会被当作Text节点对待(也就是说插入的不是HTML代码)。

语法

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

参数

nodes
要插入的一系列Node或者DOMString

返回值

undefined.

错误

例子

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.

兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
prepend
Experimental
Chrome Full support 54Edge Full support 17Firefox Full support 49IE No support NoOpera Full support 39Safari Full support 10WebView Android Full support 54Chrome Android Full support 54Firefox Android Full support 49Opera Android Full support 41Safari iOS Full support 10Samsung Internet Android Full support 6.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.

See also