javascriptselectors-apiqueryselector

why js dom api 'querySelector' select itself


I'm confused why $1 is firstBB, The querySelector('.aa .bb') call should execute under #root element.

const $1 = document.querySelector('#root').querySelector('.aa .bb');
const $2 = document.querySelector('#root').querySelector('.aa').querySelector('.bb');

document.querySelector('#result').innerHTML = `$1 is ${$1.id}; $2 is ${$2.id}`
<div class="aa" id="root">
  <div class="bb" id="firstBB">xxx</div>
  <div class="aa">
    <div class="bb" id="secondBB">xxx</div>
  </div>
</div>
<div>Result: <span id="result"></span></div>

Chrome version: 116.0.5845.188

Is this the correct behavior of querySelector?


Solution

  • This is no bug. It is the specified behaviour.

    Element: querySelector() method

    Return value

    The first descendant element of baseElement which matches the specified group of selectors. The entire hierarchy of elements is considered when matching, including those outside the set of elements including baseElement and its descendants; in other words, selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of baseElement. The first match of those remaining elements is returned by the querySelector() method.

    (tbh, i also was under the impression that it would select the second, before reading the documentation right now)