Search code examples
javascriptqueryselector

How to make a selector for direct child of the root node?


Consider that you are given a node node and you must provide all direct children given by selector Direct. Selector for direct child is:

childParent > directChild

However, the following fails with an error in console:

document.body.querySelectorAll(">div")
SyntaxError: '>div' is not a valid selector

I have a function that needs to do something on select direct child nodes, but I'm not sure how to handle this. Except of course using the for loop and analyse the children with my own code, abandoning selectors completely.

The following code does not work. Can it be changed so that it does what is intended?

function doWithDirectChildren(parentNode) {
    // does not work, the selector is invalid
    const children = parentNode.querySelector(">.shouldBeAffected");
    for(const direct of children) {
        // do something with the direct child
    }
}

I'm asking for a solution, not a workaround.


Solution

  • The proper way to do this is with the :scope psuedo class.

    According to the documentation at MDN:

    When used from a DOM API such as querySelector(), querySelectorAll(), matches(), or Element.closest(), :scope matches the element on which the method was called.

    For example:

    let parent = document.querySelector('#parent');
    let scoped = parent.querySelectorAll(':scope > span');
    
    Array.from(scoped).forEach(s => {
      s.classList.add('selected');
    });
    .selected {
      background: yellow;
    }
    <div id="parent">
      <span> Select Me </span> <br>
      <span> Me Too </span>
    </div>
    <span> Not Selected </span>