How to get elements with multiple classes

Say I have this:

<div class="class1 class2"></div>

How do I select this div element?

document.getElementsByClassName('class1')[0].getElementsByClassName('class2')[0]

That does not work.

I know that, in jQuery, it is $('.class1.class2'), but I'd like to select it with vanilla JavaScript.


Solution 1:

It's actually very similar to jQuery:

document.getElementsByClassName('class1 class2')

MDN Doc getElementsByClassName

Solution 2:

AND (both classes)

var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");

OR (at least one class)

var list = document.querySelectorAll(".class1,.class2");

XOR (one class but not the other)

var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");

NAND (not both classes)

var list = document.querySelectorAll(":not(.class1),:not(.class2)");

NOR (not any of the two classes)

var list = document.querySelectorAll(":not(.class1):not(.class2)");