Read more

How to find child nodes that match a selector with JavaScript

Arne Hartherz
August 04, 2023Software engineer at makandra GmbH

Using querySelector or querySelectorAll in JavaScript, you can easily find descendants of a node that match a given selector.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

But what if you want to find only children (i.e. direct descendants) of an element?
Easy: use :scope. It references the element on which DOM API methods are being called:

element.querySelectorAll(':scope > .your-selector')

Example

Consider this HTML

<body>
  <div id="container1">
    <div id="container1a">foo</div>
    <div id="container1b">bar</div>
    <div id="container1c">baz</div>
  </div>
  <div id="container2">
    Hello Universe
  </div>
</body>

without :scope

A simple document.body.querySelectorAll('div') will return a NodeList with 5 items, i.e. all 5 divs from above.

with :scope

Using document.body.querySelectorAll(':scope > div') you'll receive a NodeList with the 2 children of body:

  1. The container1 element
  2. The container2 element

Browser Support

:scope is supported in all browsers Show archive.org snapshot for the JavaScript DOM API.

Posted by Arne Hartherz to makandra dev (2023-08-04 15:07)