How to select element with multiple classes [duplicate]
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)");
Solution 3:
querySelectorAll with standard class selectors also works for this.
document.querySelectorAll('.class1.class2');
Solution 4:
As @filoxo said, you can use document.querySelectorAll
.
If you know that there is only one element with the class you are looking for, or you are interested only in the first one, you can use:
document.querySelector('.class1.class2');
BTW, while .class1.class2
indicates an element with both classes, .class1 .class2
(notice the whitespace) indicates an hierarchy - and element with class class2
which is inside en element with class class1
:
<div class='class1'>
<div>
<div class='class2'>
:
:
And if you want to force retrieving a direct child, use >
sign (.class1 > .class2
):
<div class='class1'>
<div class='class2'>
:
:
For entire information about selectors:
https://www.w3schools.com/jquery/jquery_ref_selectors.asp
Solution 5:
Okay this code does exactly what you need:
HTML:
<div class="class1">nothing happens hear.</div>
<div class="class1 class2">This element will receive yout code.</div>
<div class="class1">nothing happens hear.</div>
JS:
function getElementMultipleClasses() {
var x = document.getElementsByClassName("class1 class2");
x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();
Hope it helps! ;)