Explain Codes LogoExplain Codes Logo

How to get elements with multiple classes

javascript
advanced-selectors
css-selectors
dom-manipulation
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

Fast and efficient with querySelectorAll, catching all elements with your specified classes:

let multiClassElements = document.querySelectorAll('.class1.class2'); //Say hello to all our .class1.class2 pals!

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:

let elementsWithoutThirdClass = document.querySelectorAll('.class1.class2:not(.class3)'); //Who needs .class3 anyway? Not us!

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:

let firstBorn = document.querySelectorAll('.parent > .child'); //Parental favouritism, CSS style. let anyHeir = document.querySelectorAll('.grandparent .child'); //Even the black sheep of the family.

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:

let loneWolf = document.querySelector('.class1.class2'); //Because he said he wants to be alone.

Soldiers to array conversion

If NodeList is a raw recruit, convert it into a battle-hardened array for advanced maneuvers:

let badassArray = Array.from(document.querySelectorAll('.class1.class2')); //Arranged and ready for action!

The universe is in a constant state of flux

Webpages are dynamic creatures. Keep your selections current with MutationObserver — your private detective tracking changes.