代码之家  ›  专栏  ›  技术社区  ›  Jens Törnell

javascript从replaceWith返回一些内容

  •  -1
  • Jens Törnell  · 技术社区  · 7 年前

    我已经创建了一个JavaScriptWeb组件,其中一个元素被一组HTML元素完全替换。

    为了做到这一点,我用 replaceWith . 我的问题是我需要跟踪新创建的元素。我该怎么做?我使用的是普通JSES6,而不是jquery。

    let element = document.querySelector('div');
    let another = document.querySelector('h2');
      
    element.replaceWith(another);
    <div>
    Replace this content
    </div>
    
    <h2>Heading 1</h2>
    <h2>Heading 2</h2>
    <h2>Heading 3</h2>

    https://jsfiddle.net/n9q0x86a/1/

    1 回复  |  直到 7 年前
        1
  •  3
  •   Roko C. Buljan    7 年前

    我创建了一个javascript Web组件,其中一个元素完全替换为 HTML元素集

    如果你想搬家,你的陈述是错误的 全部的 所需元素代替 <div> . 在这种情况下,您需要使用 querySelectorAll() MDN 方法。这反过来会让你相信你所期望的: 所有目标选择器的集合 :

    const element = document.querySelector('#replaceMe');
    const another = document.querySelectorAll('.moveMe');
      
    element.replaceWith(...another);
    console.log("Replaced #%s with %i elements", element.id, another.length);
    
    // let's try to manipulate our stored elements:
    [...another].forEach(el => el.style.color = 'red');
    <div data-info="This DIV should stay">
      <div id="replaceMe" data-info="this DIV should be replaced">
      Replace this content
      </div>
    </div>
    
    <h1 class="moveMe">Heading 1</h2>
    <h2 class="moveMe">Heading 2</h2>
    <p class="moveMe">Paragraph</p>

    https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax