Search code examples
javascriptforeachparent-childgetelementbyid

Get parent and child ID inside for each


How do I get for each id and children's id for each parent, and how do I get the id and parent id for each child in the code described below?

Is it correct to write if {} in foreach? What is the best way to solve this.

     var aw = document.getElementById("container").className;   
     if(aw == 'activ-window'){

     var divs = document.getElementById("container").querySelectorAll('.activ-window *'); 
     var elements = "";
     divs.forEach(function(elem){
     elements += elem.id;
     if (elem.firstChild) { //is parent
         "My id:" + elem.id + "My children id:" //elem.id.child??
     }
     if (elem.//is child) {
         "My id:" + elem.id + "My parent id:" //elem.id.parent??
     }
     });
     
     
     document.getElementById("demo").innerHTML = elements;
     }

<div id="container" class="activ-window">
    <div id="parent1">
        <div id="child-1-1" ></div>
        <div id="child-1-2" ></div>
    </div>
    <div id="parent2">
        <div id="child-2-1" ></div>
        <div id="parent3" >
             <div id="child-3-1" ></div>
             <div id="child-3-2" ></div>
             <div id="child-3-3" ></div>
        </div>
    </div>
</div>

<div id="demo"></div>


Solution

  • First of all, using that many ids is a terrible practice.

    Secondly, "querySelector" is a child selector. So

    var divs = document.getElementById("container").querySelectorAll('.activ-window *'); 
    

    doesn't select anything because #container doesn't have any child with class name active-window.

    Third, It's not clear what type output you want to achive. Is it a map of DOM items or an array of ids, etc? But generally speaking, the best way is the method called recursion. Since it's a complex concept, it will be better if you watch this video: https://laracasts.com/series/building-alpinejs/episodes/2