Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementsByClassName exact match to class

Tags:

javascript

There are two similar classes - 'item' and 'item one'

When I use document.getElementsByClassName('item') it returns all elements that match both classes above.

How I can get elements with 'item' class only?

like image 528
Marat Avatar asked Sep 02 '26 04:09

Marat


2 Answers

document.querySelectorAll('.item:not(.one)');

(see querySelectorAll)

The other way is to loop over the what document.getElementsByClassName('item') returns, and check if the one class is present (or not):

if(element.classList.contains('one')){
  ...
}
like image 155
nice ass Avatar answered Sep 03 '26 16:09

nice ass


The classname item one means the element has class item and class one.

So, when you do document.getElementsByClassName('item'), it returns that element too.

You should do something like this to select the elements with only the class item:

e = document.getElementsByClassName('item');
for(var i = 0; i < e.length; i++) {
    // Only if there is only single class
    if(e[i].className == 'item') {
        // Do something with the element e[i]
        alert(e[i].className);
    }
}

This will check that the elements have only class item.

Live Demo

like image 33
ATOzTOA Avatar answered Sep 03 '26 17:09

ATOzTOA