Search code examples
javascriptfor-loopforeachgetparent-child

Get id of child elements


I need to get the id from all the child elements, which are in the parent class = "demo", but if the parent class = "demo" has id = "simone" I don't need to get the child id. How to achieve this?

If is simone, don't get children's id, else get children's id?

       var name;
     var divsname = document.querySelectorAll('.demo *');
     divsname.forEach(function(div){
        
        if (div.hasAttribute("id")) {
        name += "Name: "+div.getAttribute("id")+", "; 
        }else{
            
        }
        document.getElementById("get-demo").innerHTML = name;
    console.log(name);
     });
<div id="maja" class="demo"><div id="maja-child"></div></div>
<div id="alex" class="demo"><div id="alex-child"></div></div>
<div id="simone" class="demo"><div id="simone-child"></div></div>
<div id="pit" class="demo"><div id="pit-child"></div></div>

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


Solution

  • Just use parentElement.getAttribute("id"),

    ParentElement() will retrun parent of child element you can use exeption

    div.parentElement.getAttribute("id") !== "simone"

    will return false if id is simone.

    Example

    if (div.hasAttribute("id") && div.parentElement.getAttribute("id") !== "simone") {
          name += "Name: "+div.getAttribute("id")+", "; 
    } 
    

    This full script

    window.onload = () => 
    {
    var name = '', divsname = document.querySelectorAll('.demo *');
    
     divsname.forEach(function(div){
        if (div.hasAttribute("id") && div.parentElement.getAttribute("id") !== "simone") {
          name += "Name: "+div.getAttribute("id")+", "; 
        } 
        document.getElementById("get-demo").innerHTML = name;
     });
    }