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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)