Home > other >  Append child element in parent?
Append child element in parent?

Time:10-12

HTML elements are taken from the container. If the parent node has a child, make a button and insert child.id from child in the button. Everything works in the code, but does not want appendChild (h2);

It should look like:

<button id = "parent2"> <h2> child1 </h2> <h2> child2 </h2> </button>
<div id="container">
    <div id="parent1"></div>
    <div id="parent2">
        <div id="child1"></div>
        <div id="child2"></div>
        <div id="child3"></div>
    </div>
</div>
<p id="demo"></p> 
var parent = document.getElementById("container").querySelectorAll("*");

for (let i = 0; i < parent.length; i  ) {
    if(parent[i].hasChildNodes()){
         var btn = document.createElement("BUTTON");  
         btn.id = parent[i].id;                  
         document.getElementById("demo").appendChild(btn); 
    }
    
    let children = parent[i].childNodes;
    
    for (let i = 0; i < children.length; i  ) {
        if(children[i]){
         var h2 = document.createElement("H2");  
         h2.innerHTML = children[i].id;                  
         parent[i].appendChild(h2); 
        }else{}
    }
    }

CodePudding user response:

There are many mistakes in your code:

  • This document.getElementById("container").querySelectorAll("*"); does select all children of a container (nested ones too).
  • You can not nest two loops that iterate over the same variable i.
  • childNodes does not return only the 3 divs you want, but also all the nodes that represent the spaces/newlines. You need to filter them out, here few possible solutions.
  • You require h2 tags to be inserted in the button, but you insert them in parent[i]

This should work:

var parent = document
  .querySelectorAll("#container > *");

for (let i = 0; i < parent.length; i  ) {
    if(parent[i].hasChildNodes()) {
        var btn = document.createElement("BUTTON");
        btn.id = parent[i].id;
        document.getElementById("demo").appendChild(btn);

        let children = parent[i].childNodes;
        for (let j = 0; j < children.length; j  ) {
            if (children[j].nodeName !== 'DIV') continue;
            var h2 = document.createElement("H2");
            h2.innerHTML = children[j].id;
            btn.appendChild(h2);
        }
    }
}
<div id="container">
  <div id="parent1"></div>
  <div id="parent2">
      <div id="child1"></div>
      <div id="child2"></div>
      <div id="child3"></div>
  </div>
</div>
<p id="demo"></p>

  • Related