document.getElementsByClassName exact match to class

javascript

Solution

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

Problem

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?

Original source

Related problems