mattsh mattsh - 2 years ago 153
Javascript Question

Using querySelectorAll to Retrieve Direct Children

I am able to do this:

<div id="myDiv">
<div class="foo"></div>

myDiv = getElementById("myDiv");
myDiv.querySelectorAll("#myDiv > .foo");

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

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

I ought to be able to leave the
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?

Answer Source

Good question, but as you see there is no way to do "combinator rooted queries" as John Resig names them.

However, in some cases you can just skip .querySelectorAll and use other good old-fashioned DOM API features. Instead of the unsupported myDiv.querySelectorAll("> *") you can just write myDiv.children, for example.

Unfortunately I can't think of a way to handle your situation without adding more custom filter logic (e.g. find myDiv.getElementsByClassName("foo") whose .parentNode === myDiv), and obviously not ideal if you're trying to support one code path that really just wants to take an arbitrary selector string as input and a list of matches as output! But if like me you ended up asking this question simply because you got stuck thinking "all you had was a hammer" don't forget there are a variety of other tools the DOM offers too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download