简体   繁体   English

在 Vanilla JS 中使用 replaceWith 用 DOMstring 或多个元素替换元素

[英]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()的签名接受可变数量的NodeDOMString参数

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM