Using querySelectorAll to retrieve direct children

I am able to do this:

<div id="myDiv">
   <div class="foo"></div>
</div>
myDiv = getElementById("myDiv");
myDiv.querySelectorAll("#myDiv > .foo");

That is, I can successfully retrieve all the direct children of the myDiv element that have class .foo.

The problem is, it bothers me that I must include the #myDiv in the selector, because I am running the query on the myDiv element (so it is obviously redundant).

I ought to be able to leave the #myDiv off, but then the selector is not legal syntax since it starts with a >.

Does anyone know how to write a selector which gets just the direct children of the element that the selector is running on?

You’re correct that when you use querySelectorAll, it expects a valid CSS selector, and starting with > isn’t allowed since it’s not a complete selector on its own. However, there’s a simple way to achieve what you’re trying to do without the redundancy of including the parent element’s ID in the selector.

Here’s how you can do it:

javascript

Copy code

myDiv = document.getElementById("myDiv");
myDiv.querySelectorAll(":scope > .foo");

Explanation:

  • :scope is a pseudo-class that represents the element on which the method is called (myDiv in this case).
  • By using :scope > .foo, you’re telling the browser to find all direct children of myDiv that have the class foo, without needing to explicitly reference myDiv in the selector.

This way, your selector is cleaner and avoids the redundancy of repeating #myDiv.