我找不到replaceWith使用多個元素/節點的 vanilla javascript 示例。
給定帶有多個子元素的 HTML:
<span id="parent"><span>Hardware:</span> <br>
the <span id="oldChild">physical</span> components of a <span>computer</span>.</span>
我可以用多個元素和文本節點(這些跨度后面的逗號和空格)replaceWith交換任何一個child跨度,比如#oldChild:
let 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 字串(即最好使用其他資料結構,如物件和陣列)。
uj5u.com熱心網友回復:
我可以
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 的字串,你可以......
- 創建臨時元素
- 設定
innerHTML - 將該元素的子節點傳遞給
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/338446.html
標籤:javascript html dom
