我找不到使用多个元素/节点的香草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()的签名接受可变数目的Node
或DOMString
参数…
语法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的字符串,你可以…
- 创建临时元素 设置
- 将该元素的子节点传递给
replaceWith
innerHTML
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>