DEV Community

mostafalaravel
mostafalaravel

Posted on

 

How to find a child (not direct child) of a specific element by Id(parent Id)?

Hello ,

<parent id="abc-1">

  <child-1>
    <child-2></child-2>
        <child-3>
            <child-4 class="my-class">Hey my data</child-4>
    </child-3>
   </child-1>

  <child-5></child-5>

</parent>
Enter fullscreen mode Exit fullscreen mode


`

I would like to get the content of the element where the class name is my-class

This element exists inside parent with the id="abc-1" but we don't know on which level, maybe child or child of child or ... but we are sure that the class name is my-class

Top comments (1)

Collapse
 
rehmatfalcon profile image
Kushal Niroula

You could get the element with the id and then use querySelector on it.

For example,

const parentElm = document.querySelector("#abc-1");
const childElm = parentElm.querySelector(".my-class"); 
Enter fullscreen mode Exit fullscreen mode

Of course you should always check if parentElm exists or not.

You could also use nested selector for the same.

const childElm = document.querySelector("#abc-1 .my-class");
Enter fullscreen mode Exit fullscreen mode