Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result difference between CSS selectors and querySelector function

I don't understand the console outputs of this code, especially since the CSS code targets the right element but not the querySelector function.

let firstChild = document.querySelector('BODY > :first-child');
console.log(firstChild.querySelector(':first-child > :first-child'));
console.log(firstChild.querySelector(':first-child'));
BODY > :first-child > :first-child > :first-child  {
  color: red;
}
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div class="D1">
      <div class="D2">
        <div>A</div>
        <div>B</div>
      </div>
    </div>
  </body>
</html>

1 Answers

foo.querySelector matches the first element inside foo that the selector matches.

This:

let firstChild = document.querySelector('BODY > :first-child');

Matches <div class="D1">

Then:

firstChild.querySelector(':first-child > :first-child')

Matches <div class="D2"> because:

  • <div class="D2"> is inside firstChild
  • <div class="D1"> matches :first-child (it is the first child of body)
  • <div class="D2"> matches :first-child (it is the first child of D1)
firstChild.querySelector(':first-child')

… gives a similar result, It just doesn't care about the second condition above.


In short, you get different results because querySelector does not add an implicit "descendant of foo" to the selector itself, nor does it require that every element matched is a descendant of foo (only the final element needs to match that)).

like image 189
Quentin Avatar answered Dec 31 '25 08:12

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!