在香草JS中使用replaceWith将一个元素替换为DOMstring或多个元素



我找不到使用多个元素/节点的香草javascriptreplaceWith的例子.

给定具有多个子元素的HTML:

<span id="parent"><span>Hardware:</span> <br>
the <span id="oldChild">physical</span> components of a <span>computer</span>.</span>

我可以使用replaceWith交换child跨度中的任何一个,例如#oldChild,具有多个元素和文本节点(这些跨度后面的逗号和空格):

const newSpans = 
"<span id="newChild1">kickable</span>, 
<span id="newChild2">throwable</span>, 
<span id="newChild3">punchable</span>"

下面的语法有什么问题?我如何将这个动态生成的代码(上面)转换为replaceWith可接受的参数?

oldChild.replaceWith( newSpans );

非常感谢Phil,下面:

const temp = document.createElement("div") 
temp.innerHTML = newSpans
const oldChild = document.getElementById("oldChild")
oldChild.replaceWith(...temp.childNodes)

注意:Phil明智地建议最好避免HTML字符串(即最好使用其他数据结构,如对象和数组)。

我可以使用replaceWith来交换任何一个具有多个元素和文本节点的子跨度

Element.replaceWith()的签名接受可变数目的NodeDOMString参数…

语法
replaceWith(...nodes)

…所以,是的

// helper / utility function
const createSpan = (id, textContent) => Object.assign(document.createElement("span"), { id, textContent })
document.getElementById("oldChild").replaceWith(
createSpan("newChild1", "kickable"),  // Node
", ",                                 // DOMString
createSpan("newChild2", "throwable"), // Node
", ",                                 // DOMString
createSpan("newChild3", "punchable")  // Node
)
#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>


您还可以构建一个节点数组传递给replaceWith并使用扩展语法

const newSpans = [
createSpan("newChild1", "kickable"),
createSpan("newChild2", "throwable"),
createSpan("newChild3", "punchable")
]
// Add in separators
const newNodes = newSpans.flatMap(s => [s, ", "]).slice(0, -1)
document.getElementById("oldChild").replaceWith(...newNodes) // spread

如果你只有一个包含HTML的字符串,你可以…

  1. 创建临时元素
  2. 设置innerHTML
  3. 将该元素的子节点传递给replaceWith

let newSpans = 
`<span id="newChild1">kickable</span>, 
<span id="newChild2">throwable</span>, 
<span id="newChild3">punchable</span>`
const tmp = document.createElement("div")
tmp.innerHTML = newSpans
document.getElementById("oldChild").replaceWith(...tmp.childNodes)
#newChild1 { color: green; }
#newChild2 { color: orange; }
#newChild3 { color: red; }
/* just showing that #oldChild and the <div> aren't included */
#oldChild, div { background: red; }
<span id="parent"><span>Hardware:</span> <br> the <span id="oldChild">physical</span> components of a <span>computer</span>.</span>

最新更新