I can't find examples of vanilla javascript replaceWith
using multiple elements/nodes .
Given HTML with numerous children:
<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):
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
The signature for Element.replaceWith() accepts a variable number of Node
or DOMString
arguments
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.