Weird behaviour when using querySelector [duplicate]

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)