How to get elements with multiple classes
Fast and efficient with querySelectorAll, catching all elements with your specified classes:
This fetches all elements wearing the badges of .class1 AND .class2. Your prize: a NodeList ready to loop through or be whipped up into an array via Array.from() just like scrambled eggs.
Advanced selection techniques
When your selection criteria becomes a high IQ puzzle, make use of advanced CSS selectors.
Hunting multiple classes at once
Forget shooting two birds with one stone, grab a whole flock! querySelectorAll('.class1.class2, .class3') snags elements with any of these class combinations — spreading the net wider!
Avoiding the unwanted
Dodging a bullet or avoiding certain classes? Enter :not selector:
This nabs all elements stamped with .class1.class2 but straight up ghosts any sporting also .class3.
Family matters: child vs descendant
Parent-child relationships are tricky. Good news: CSS understands. > selector for immediate offspring, whitespace for any descendant:
Arsenal of tools at your disposal
While querySelectorAll is your trusty multi-tool, there are other weapons in the arsenal, each with its unique strengths.
Heritage and old systems
You might stumble upon a getElementsByClassName in the old codebase or legacy systems. Beware, unlike querySelectorAll, it treats combined classes separated by a space like a bull treats a red flag.
jQuery collections vs Vanilla JS independence
Used to the convenience of jQuery's $('.class1.class2')? No stress, querySelectorAll does the same without having to rely on jQuery — freeing you from dependencies!
Pro techniques and unseen corners
Single out with querySelector
The lone wolf in your element pack? querySelector to the rescue — zeroing on the first matching element:
Soldiers to array conversion
If NodeList is a raw recruit, convert it into a battle-hardened array for advanced maneuvers:
The universe is in a constant state of flux
Webpages are dynamic creatures. Keep your selections current with MutationObserver — your private detective tracking changes.
Was this article helpful?
