La méthode ParentNode.prepend
insère un jeu d'objets Node
(noeud) ou DOMString
(chaîne de caractères) avant le premier enfant de ParentNode
. Les objets DOMString
sont insérés comme équivalant des noeuds Text
.
Syntaxe
ParentNode.prepend(nodesToPrepend);
Paramètres
Valeur retournée
undefined
(indéfini).
Exceptions
HierarchyRequestError
: Le noeud ne peut pas être inséré au point spécifié dans la hiérarchie.
Exemples
Ajout d'un élément
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> ]
Ajout d'un texte
var parent = document.createElement("div");
parent.append("Some text");
parent.prepend("Headline: ");
console.log(parent.textContent); // "Headline: Some text"
Ajout d'un élément et d'un texte
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()
est non accessible
La méthode prepend()
n'est pas comprise dans l'instruction with
. Voir Symbol.unscopables
pour plus d'informations.
var parent = document.createElement("div");
with(parent) {
prepend("foo");
}
// ReferenceError: prepend is not defined (prepend n'est pas défini)
Polyfill
vous pouvez utiliser le polyfill pour la méthode prepend()
si elle n'est pas disponible :
// 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]);
Spécification
Spécification | Statut | Commentaire |
---|---|---|
DOM La définition de 'ParentNode.prepend()' dans cette spécification. |
Standard évolutif | Définition initiale. |
Compatibilité des navigateurs
BCD tables only load in the browser