How to get elements with multiple classes

Nathan Prometheus picture Nathan Prometheus · Aug 25, 2011 · Viewed 159.6k times · Source

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.

Answer

Joe picture Joe · Aug 25, 2011

It's actually very similar to jQuery:

document.getElementsByClassName('class1 class2')

MDN Doc getElementsByClassName