--- title: Element.prepend() slug: Web/API/Element/prepend translation_of: Web/API/Element/prepend tags: - API - DOM - Method - Node - Element - Reference - prepend browser-compat: api.Element.prepend ---
Element.prepend
方法可以在父节点的第一个子节点之前插入一系列{{domxref("Node")}}对象或者{{domxref("DOMString")}}对象。{{domxref("DOMString")}}会被当作{{domxref("Text")}}节点对待(也就是说插入的不是HTML代码)。
Element.prepend((Node or DOMString)... nodes);
nodes
undefined
.
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> ]
var parent = document.createElement("div"); parent.append("Some text"); parent.prepend("Headline: "); console.log(parent.textContent); // "Headline: Some 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> ]
Element.prepend()
is unscopableprepend()不能在with语句内使用,详情参考
{{jsxref("Symbol.unscopables")}}。
var parent = document.createElement("div"); with(parent) { prepend("foo"); } // ReferenceError: prepend is not defined
使用下面的代码在IE9或更高版本中模拟prepend()
方法:
// from: https://github.com/jserz/js_piece/blob/master/DOM/Element/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 |
---|---|---|
{{SpecName('DOM WHATWG', '#dom-Element-prepend', 'Element.prepend()')}} | {{Spec2('DOM WHATWG')}} | Initial definition. |
{{Compat("api.Element.prepend")}}