代码之家  ›  专栏  ›  技术社区  ›  Andrei Cleland

使用replaceWith将元素替换为DOMstring或Vanilla JS中的多个元素

  •  1
  • Andrei Cleland  · 技术社区  · 3 年前

    我找不到普通javascript的示例 replaceWith 使用 多个元素/节点 .

    给定具有许多子级的HTML:

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

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

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

    下面的语法有什么问题?以及如何将此动态生成的代码(如上)转换为可接受的参数 替换为 ?

    oldChild.replaceWith( newSpans );
    

    非常感谢 Phil 在下面

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

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

    1 回复  |  直到 3 年前
        1
  •  4
  •   Phil    3 年前

    我可以使用吗 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>

    你也可以建立一个数组 节点 传递给 替换为 和使用 spread syntax

    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. 将该元素的子节点传递给 替换为

    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>硬件:</span>&书信电报;br><span id=“oldChild”>物理</span><span>计算机</span></span>