Syntaxe
[Throws, Unscopable] void ChildNode.replaceWith((Node ou DOMString)... nodes);
Paramètres
Exceptions
HierarchyRequestError
: Le noeud ne peut pas être inséré au point spécifié dans la hiérarchie.
Exemples
Utilisation de replaceWith()
var parent = document.createElement("div");
var enfant = document.createElement("p");
parent.appendChild(enfant);
var span = document.createElement("span");
enfant.replaceWith(span);
console.log(parent.outerHTML);
// "<div><span></span></div>"
ChildNode.replaceWith() n'est pas accessible
La méthode replaceWith()
n'est pas comprise dans une instruction with. Voir Symbol.unscopables
pour plus d'informations.
with(node) {
replaceWith("foo");
}
// ReferenceError: replaceWith n'est pas défini
Prothèse d'émulation
Vous pouvez utiliser une prothèse d'émulation pour la méthode replaceWith()
pour Internet Explorer 10 et plus avec le code suivant :
function ReplaceWith(Ele) {
'use-strict'; // For safari, and IE > 10
var parent = this.parentNode,
i = arguments.length,
firstIsNode = +(parent && typeof Ele === 'object');
if (!parent) return;
while (i-- > firstIsNode){
if (parent && typeof arguments[i] !== 'object'){
arguments[i] = document.createTextNode(arguments[i]);
} if (!parent && arguments[i].parentNode){
arguments[i].parentNode.removeChild(arguments[i]);
continue;
}
parent.insertBefore(this.previousSibling, arguments[i]);
}
if (firstIsNode) parent.replaceChild(Ele, this);
}
if (!Element.prototype.replaceWith)
Element.prototype.replaceWith = ReplaceWith;
if (!CharacterData.prototype.replaceWith)
CharacterData.prototype.replaceWith = ReplaceWith;
if (!DocumentType.prototype.replaceWith)
DocumentType.prototype.replaceWith = ReplaceWith;
Spécification
Spécification | État | Commentaire |
---|---|---|
DOM La définition de 'ChildNode.replacewith()' dans cette spécification. |
Standard évolutif | Définition initiale. |
Compatibilité des navigateurs
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.