CSS SELECTORISMS A small document describing possible misunderstandings of css selectors. CH.1 SELECTING THE FIRST ELEMENT As of writing I ran into a problem using `:first-child` with `document.querySelector`. I have learned this selector literally means "select the element **if it is the first child**". It is super important to emphasize this, because if you have, for example:


my name is lee

Your selector `p:first-child` will not match! For the simple reason that *it is not the first child of ``*. So how can we select the first child of a specific type? `:first-of-type` ! document.querySelector('p') == document.querySelector('p:first-of-type') In CSS files though, the former selects **all** `

` elements, whereas the latter just selects the first. CH.2 `QUERYSELECTOR` DOES NOT SCOPE TO THE ELEMENT It turns out when you do something like: // html:

const b = document.querySelector('.b'); b.querySelector('.a .c'); What do you expect the result to be? On my first and only try, I guessed it would not select anything. But no, it does select `.c`! This is because `querySelector` **does not scope to the element it's called from**! It scopes all selectors to `:root`, which is ``. To scope the selector is very simple though: `b.querySelector(':scope .a .c')` which would then return nothing as we expect.