简体   繁体   中英

How to append only node's child nodes?

Assuming the following node(s) (which is/are actually not generated like this):

let outer = document.createElement('div');
outer.innerHTML = `
  <div>foo</div>
  <div>bar</div>
  .
  .
  .
  <div>whatever</div>
`;

Now I can append outer to another node:

let body = document.querySelector('body');
body.append(outer);

But how to append only the inner of outer without loosing event listeners etc.?

通过使用...语法来传播一个可迭代对象,调用append() outer的每个孩子作为单独的参数。

body.append(...outer.children);

To answer your "without losing event handlers" - it turns out your are not when you append

Without delegation

 let outer = document.createElement('div'); outer.classList.add("outer") outer.innerHTML = ` <div class="foo" onclick="console.log('Foo clicked')">foo</div> <div class="bar">bar</div> <div>whatever</div> `; let body = document.querySelector('body'); body.append(outer); body.append(...outer.children);
 .outer { height:100px; width:100px; border: 1px solid red;}

With delegation from body

 let outer = document.createElement('div'); outer.classList.add("outer") outer.innerHTML = ` <div class="foo">foo</div> <div class="bar">bar</div> <div>whatever</div> `; let body = document.querySelector('body'); body.append(outer); body.append(...outer.children); body.addEventListener("click", e => { const tgt = e.target; if (tgt.matches(".foo")) console.log("Foo clicked") else if (tgt.matches(".bar")) console.log("Bar clicked") })
 .outer { height:100px; width:100px; border: 1px solid red;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM