Get elements by class A or B in JavaScript

CookieMonster picture CookieMonster · Feb 18, 2014 · Viewed 7.5k times · Source

Is it possible to get elements that have one of the specified classes? This is not the same as getting elements that have all of the specified classes.

For example, I want to capture all elements whose class list contains either one, two, or three.

Maybe something like this:

var oneTwoThree = document.getElementsByClassName("one, two, three");

I also do not want to use jQuery. Is the only option to getElementsByClassName for each class and combine them?

Answer

Tibos picture Tibos · Feb 18, 2014

querySelector accepts pretty much any CSS selector:

var oneTwoThree = document.querySelectorAll('.one, .two, .three');