[英]using replaceWith to replace an element with a DOMstring or multiple elements in Vanilla JS
I can't find examples of vanilla javascript replaceWith
using multiple elements/nodes .我找不到使用多个元素/节点的 vanilla javascript
replaceWith
示例。
Given HTML with numerous children:给定带有多个子元素的 HTML:
<span id="parent"><span>Hardware:</span> <br>
the <span id="oldChild">physical</span> components of a <span>computer</span>.</span>
Can I use replaceWith
to swap any one of the child
spans, say #oldChild
, with multiple elements AND text nodes (the commas and spaces following these spans):我可以使用
replaceWith
来交换任何一个child
跨度,比如#oldChild
,与多个元素和文本节点(这些跨度后面的逗号和空格):
let newSpans =
"<span id="newChild1">kickable</span>,
<span id="newChild2">throwable</span>,
<span id="newChild3">punchable</span>"
Is there any other vanilla method that will work like this?:有没有其他香草方法可以像这样工作?:
oldChild.replaceWith( newSpans );
Can I use
replaceWith
to swap any one of the child spans with multiple elements AND text nodes我可以使用
replaceWith
将任何一个子跨度与多个元素和文本节点交换replaceWith
The signature for Element.replaceWith() accepts a variable number of Node
or DOMString
arguments Element.replaceWith()的签名接受可变数量的
Node
或DOMString
参数
Syntax
句法
replaceWith(...nodes)
so, yes所以,是的
// helper / utility function const createSpan = (id, textContent) => Object.assign(document.createElement("span"), { id, textContent }) document.getElementById("oldChild").replaceWith( createSpan("newChild1", "kickable"), ", ", createSpan("newChild2", "throwable"), ", ", createSpan("newChild3", "punchable") )
#newChild1 { color: green; } #newChild2 { color: orange; } #newChild3 { color: red; }
<span id="parent"><span>Hardware:</span> <br> the <span id="oldChild">physical</span> components of a <span>computer</span>.</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.