The DOM Query Trick Every Front-End Dev Needs
The DOM Query Trick Every Front-End Dev Needs
I just found a slick trick for nailing DOM queries. It’s called :scope, and it’s a lifesaver. Ready to make your selectors razor-sharp?
Selecting the right elements feels like a guessing game sometimes. This approach lets you target exactly what you need, no hacks required.
Take this HTML example:
- A
- B
- C
- D
Here’s the challenge
You want only the odd <li> elements under the <ul>. My first stab was:
document.querySelectorAll(" > :nth-child(odd)")
Nope. The above query crashes because the direct descendant (>) has no anchor. This isn’t a valid CSS selector. So, I tried:
document.querySelectorAll(“* > :nth-child(odd)”)
It runs, but grabs every <strong> instead, way off target.
Here’s the solution: Lean on the :scope pseudo-class. Try this:
document.querySelectorAll(“:scope > :nth-child(odd)”)
Check this demo to see it in action:
- A
- B
- C
- D
Click the <ul>, and odd-numbered <li> elements light up in snazzy limegreen.
Every odd <li> gets styled, no extras.
Pro tip: :scope has been rock-solid in browsers since Edge caught up in 2019.
Give it a spin in your next project.
via Amit Kumar
