Marat
Marat

Reputation: 167

document.getElementsByClassName exact match to class

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?

Upvotes: 6

Views: 16817

Answers (5)

fxlemire
fxlemire

Reputation: 936

If you have jQuery, it can be done using the attribute equals selector syntax like this: $('[class="item"]').

If you insist on using document.getElementsByClassName, see the other answers.

Upvotes: 2

ATOzTOA
ATOzTOA

Reputation: 35950

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

Upvotes: 5

nbrooks
nbrooks

Reputation: 18233

You can use Array.filter to filter the matched set to be only those with class test:

var elems = Array.filter( document.getElementsByClassName('test'), function(el){
    return !!el.className.match(/\s*test\s*/);
});

Or only those with test but not one:

var elems = Array.filter( document.getElementsByClassName('test'), function(el){
    return el.className.indexOf('one') < 0;
});

(Array.filter may work differently depending on your browser, and is not available in older browsers.) For best browser compatibility, jQuery would be excellent for this: $('.test:not(.one)')

Upvotes: 1

Mara Ormston
Mara Ormston

Reputation: 1856

You're going to want to make your own function for exact matches, because spaces in a class means it has multiple classes. Something like:

function GetElementsByExactClassName(someclass) {
  var i, length, elementlist, data = [];

  // Get the list from the browser
  elementlist = document.getElementsByClassName(someclass);
  if (!elementlist || !(length = elementlist.length))
    return [];

  // Limit by elements with that specific class name only
  for (i = 0; i < length; i++) {
    if (elementlist[i].className == someclass)
      data.push(elementlist[i]);
  }

  // Return the result
  return data;
} // GetElementsByExactClassName

Upvotes: 1

nice ass
nice ass

Reputation: 16709

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')){
  ...
}

Upvotes: 5

Related Questions