JavaScript从replaceWith

时间:2019-01-01 20:48:26

标签: javascript dom replace

我创建了一个javascript网络组件,其中一个元素完全被一组html元素替换。

为此,我使用replaceWith。我的问题是我需要跟踪新创建的元素。我怎样才能做到这一点?我使用香草js ES6,而不是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 个答案:

答案 0 :(得分:3)

  

我创建了一个javascript网络组件,其中一个元素完全替换为一组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