Jerald
Jerald

Reputation: 4048

Element.querySelector for the element's direct child

I have some JS constant with HTML element (for example Div). I need to know if the element contains some HTML structure. For example, here is my HTML:

<div id="container">
  <table class="cls1 cls2">
    <tbody class="cls3 cls4">
      <tr class="cls5 cls6">
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>  
</div>
<div></div>
<span></span>

I have JS constant with <div id="container"> element. For example:

const div = document.querySelector('#container');

It is just an example. Actually the div doesn't contain "container" id. And I get this element from some function, so I don't know the element's CSS selector.

I need to know, if the element contains this CSS selector: table.cls1.cls2 > tbody.cls3.cls4 > tr.cls5.cls6 > td and the table.cls1.cls2 must be the direct child of the div. It would be great to use something like this:

const ok = div.querySelector('> table.cls1.cls2 > tbody.cls3.cls4 > tr.cls5.cls6 > td');

But it is not a valid selector (which starts with ">").

Upvotes: 2

Views: 53

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

You can make use of :scope pseudo class to target self and then write selectors for direct children

const ok = div.querySelector(':scope > table.cls1.cls2 > tbody.cls3.cls4 > tr.cls5.cls6 > td');

Upvotes: 3

Related Questions