Weird behaviour when using querySelector

The query selector div > div > div only means:

Find a div which has a parent and a granparent which are both also a div.

And if you start with the first child of test and check the selector, it is true. And this is the reason why only your last query selects the innermost div, since it has the first predicate (find a div with a great-great-grandparent-div) which is not fulfilled by the first child of test.

The query-selector will only test descendants, but it will evaluate the expression in scope of the whole document. Just imagine a selector like checking properties of an element - even if you only view the child element, it is still the child of its parent.


What querySelector does is it finds an element somewhere in the document that matches the CSS selector passed, and then checks that the found element is a descendant of the element you called querySelector on. It doesn't start at the element it was called on and search downwards - rather, it always starts at the document level, looks for elements that match the selector, and checks that the element is also a descendant of the calling context element. It's a bit unintuitive.

So:

someElement.querySelector(selectorStr)

is like

[...document.querySelectorAll(selectorStr)]
  .find(elm => someElement.contains(elm));

A possible solution is to use :scope to indicate that you want the selection to start at the rootDiv, rather than at document:

const rootDiv = document.getElementById('test');
console.log(rootDiv.querySelector(':scope > div').innerHTML);
console.log(rootDiv.querySelector(':scope > div > div').innerHTML);
console.log(rootDiv.querySelector(':scope > div > div > div').innerHTML);
<div>
  <div>
    <div id="test">
      <div>
        <div>
        This is content
        </div>
      </div>
    </div>
  </div>
</div>

:scope is supported in all modern browsers but Edge.


The currently accepted answer somehow provides a valid logical explanation as to what happens, but they are factually wrong.

Element.querySelector triggers the match a selector against tree algorithm, which goes from the root element and checks if its descendants do match the selector.

The selector itself is absolute, it doesn't have any knowledge of a Document and doesn't even require that your Element be appended to any. And apart from the :scope attribute, it doesn't either care with which root you called the querySelector method.

If we wanted to rewrite it ourselves, it would be more like

const walker = document.createTreeWalker(element, {
  NodeFilter.SHOW_ELEMENT,
  { acceptNode: (node) => return node.matches(selector) && NodeFilter.FILTER_ACCEPT }
});
return walker.nextNode();

const rootDiv = document.getElementById('test');
console.log(querySelector(rootDiv, 'div>div').innerHTML);

function querySelector(element, selector) {
  const walker = document.createTreeWalker(element, 
    NodeFilter.SHOW_ELEMENT,
    {
      acceptNode: (node) => node.matches(selector) && NodeFilter.FILTER_ACCEPT
    });
  return walker.nextNode();
};
<div>
  <div>
    <div id="test">
      <div>
        <div>
          This is content
        </div>
      </div>
    </div>
  </div>
</div>

With the big difference that this implementation doesn't support the special :scope selector.

You may think it's the same going from the document or going from the root element, but not only will it make a difference in terms of performances, it will also allow for using this method while the element is not appended to any document.

const div = document.createElement('div');
div.insertAdjacentHTML('beforeend', '<div id="test"><div class="bar"></div></div>')

console.log(div.querySelector('div>.bar')); // found
console.log(document.querySelector('div>.bar')); // null

In the same way, matching elements in the Shadow-DOM would not be possible if we only had Document.querySelector.

Tags:

Javascript