Метод ParentNode.prepend()
вставляет множество объектов Node
или DOMString
в начало (перед первым потомком) ParentNode
. Объекты DOMString
вставляются как Text
.
Синтаксис
ParentNode.prepend(...nodesToPrepend);
Параметры
Возвращаемое значение
undefined
.
Исключения
HierarchyRequestError
: Узел не может быть вставлен в указанную позицию данной иерархии.
Примеры
Добавление элемента в начало
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> ]
ParentNode.prepend()
не имеет области видимости
Метод prepend()
не входит в область видимости оператора with
. Смотрите Symbol.unscopables
для детальной информации.
var parent = document.createElement("div");
with(parent) {
prepend("foo");
}
// ReferenceError: prepend is not defined
Полифил
Вы можете использовать полифил, если метод prepend()
не доступный:
// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/prepend()/prepend().md
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('prepend')) {
return;
}
Object.defineProperty(item, 'prepend', {
configurable: true,
enumerable: true,
writable: true,
value: function prepend() {
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()' в этой спецификации. |
Живой стандарт | 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.