ChildNode.replaceWith()
Метод ChildNode.replaceWith()
заменяет ChildNode
в списке детей их родителя множеством Node
или DOMString
объектов. DOMString
объекты вставляются как эквивалент нод Text
.
Синтаксис
[Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes);
Параметры
Исключения
HierarchyRequestError
: Нода не может быть вставлена в указанную точку иерархии.
Примеры
Использование replaceWith()
var parent = document.createElement("div");
var child = document.createElement("p");
parent.appendChild(child);
var span = document.createElement("span");
child.replaceWith(span);
console.log(parent.outerHTML);
// "<div><span></span></div>"
ChildNode.replaceWith()
не выполним
Метод replaceWith()
не входит в область видимости оператора with
. Смотрите Symbol.unscopables
для дополнительной информации.
with(node) {
replaceWith("foo");
}
// ReferenceError: replaceWith is not defined
Полифилл
Вы можете заполнить метод replaceWith()
в Internet Explorer 10+ и выше следующим кодом:
function ReplaceWithPolyfill() {
'use-strict'; // For safari, and IE > 10
var parent = this.parentNode, i = arguments.length, currentNode;
if (!parent) return;
if (!i) // if there are no arguments
parent.removeChild(this);
while (i--) { // i-- decrements i and returns the value of i before the decrement
currentNode = arguments[i];
if (typeof currentNode !== 'object'){
currentNode = this.ownerDocument.createTextNode(currentNode);
} else if (currentNode.parentNode){
currentNode.parentNode.removeChild(currentNode);
}
// the value of "i" below is after the decrement
if (!i) // if currentNode is the first argument (currentNode === arguments[0])
parent.replaceChild(currentNode, this);
else // if currentNode isn't the first
parent.insertBefore(currentNode, this.nextSibling);
}
}
if (!Element.prototype.replaceWith)
Element.prototype.replaceWith = ReplaceWithPolyfill;
if (!CharacterData.prototype.replaceWith)
CharacterData.prototype.replaceWith = ReplaceWithPolyfill;
if (!DocumentType.prototype.replaceWith)
DocumentType.prototype.replaceWith = ReplaceWithPolyfill;
Спецификация
Specification | Status | Comment |
---|---|---|
DOM Определение 'ChildNode.replacewith()' в этой спецификации. |
Живой стандарт | Initial definition. |
Совместимость с браузерами
BCD tables only load in the browser