Home > Blockchain >  How to append only node's child nodes?
How to append only node's child nodes?

Time:06-24

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.?

CodePudding user response:

Call append() with each child of outer as a separate argument by using the ... syntax to spread an iterable.

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

CodePudding user response:

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  onclick="console.log('Foo clicked')">foo</div>
  <div >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 >foo</div>
  <div >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;}

  • Related