Filter objects by className from nodeList
Try querySelector instead.
document.querySelectorAll('.a.b');
This is likely your simplest solution.
The documentation for document.getElementsByClassName()
states it can accept a string with multiple class names (separated by a space):
var elements = document.getElementsByClassName(names); // or:
elements
is a liveHTMLCollection
of found elements.names
is a string representing the list of class names to match; class names are separated by whitespace
and also in the Examples section:
Get all elements that have both the 'red' and 'test' classes:
document.getElementsByClassName('red test')
That function can be used for both class names. Generally using querySelectorAll()
can be slower than using getElementsByClassName()
for a simple selector with class names. See comparison in this jsPerf . Related: querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript
const abElements = document.getElementsByClassName('a b');
console.log(abElements);
<div class="a"></div>
<div class="a"></div>
<div class="a b"></div>
<div class="a"></div>
<div class="a b"></div>
<div class="a"></div>
If you have an existing collection from document.getElementsByClassName()
with only the elements that have class name a
then the filter() method can be used to keep only the elements that have the second class, utilizing Element.classList.contains()
to only include elements with both class names. See a demonstration below. Because document.getElementsByClassName()
returns a returns a NodeList you will need to put the elements into an array before you can call that filter method.
ES-6 Version
The spread syntax can be used to put the elements into an array before calling the filter method.
const aElements = document.getElementsByClassName('a');
const abElements = [...aElements].filter(element => element.classList.contains('b'));
console.log(abElements);
<div class="a"></div>
<div class="a"></div>
<div class="a b"></div>
<div class="a"></div>
<div class="a b"></div>
<div class="a"></div>
ES-5 Version
Note that Element.classList has limited browser support (e.g. not in IE 9-) so in order to check for the b class without using that property, you could split the class names (using property className) into an array and use Array.indexOf():
var aElements = document.getElementsByClassName('a');
var abElements = Array.prototype.filter.call(aElements, function(element, index, aElements) {
var classNames = element.className.split(' ');
return classNames.indexOf('b') > -1;
});
console.log(abElements);
<div class="a"></div>
<div class="a"></div>
<div class="a b"></div>
<div class="a"></div>
<div class="a b"></div>
<div class="a"></div>