0

I want to check for the class name with JS. But as the element has several classes, the used command does not seem to work. How can I check for a single class?

HTML

<div class="first_class second_class third_class"> </div>

JS

var trg = e.target;

if ( trg.classList.contains('third_class') ) {

     console.log(trg);
   }
user2952265
  • 1,590
  • 7
  • 21
  • 32
  • According to [this article](https://developer.mozilla.org/en-US/docs/Web/API/Element.classList) it is supposed to work. Are you using an older browser? – sheng Dec 03 '13 at 15:33

4 Answers4

2

In jQuery:

$( "#mydiv" ).hasClass( "foo" )
Samuel
  • 2,106
  • 1
  • 17
  • 27
1

classList is not currently wiredly available.

Use either className.indexOf or className.split(...) or get classList polyfill: https://github.com/remy/polyfills

eRIZ
  • 1,477
  • 16
  • 32
1

If you want to stay with pure Javascript and avoid third party libraries

var trg = e.target;
if (trg.className.split(' ').indexOf('third_class') > -1) {
  console.log(trg);
}

If you use indexOf on the string directly, you might get false positives (for example, if you search for "foo" and you have a class "foolish" you will get a false positive).

Beware that Internet Explorer < 9 does not support indexOf. If you need to support it, either use a polyfill or a method from a third party library like jQuery.

Community
  • 1
  • 1
Samuel Bolduc
  • 18,163
  • 7
  • 34
  • 55
  • …but *here*, false *negatives* are possible: when the classes are delimited by any other form of whitespace, this won't catch them. Rather than use string manipulation and or Regex (which could fix this issue), there's less second-guessing involved in using `classList` instead of `className`, since it already knows what the individual classes are. – Barney Dec 03 '13 at 15:49
  • I wondered about it while writing it, but I thought "oh well class names are always separated by spaces" ... I still don't know in which case this is not true, but I guess we never know... – Samuel Bolduc Dec 03 '13 at 15:55
1

contains is an underscore method — the native array method it uses is indexOf — however neither of these will work because the object returned by classList isn't a real array, so we need to apply it to the array's indexOf method:

if ( Array.prototype.indexOf.call( trg.classList, 'third_class' ) > -1 ) {
    console.log(trg);
}

If you are using underscore though:

if ( _.toArray( trg.classList ).contains( 'third_class' ) ) {
    console.log(trg);
}
Barney
  • 16,181
  • 5
  • 62
  • 76
  • Wouldn't it be better to split the classes into an array and *then* calling indexOf? You will also avoid false positives – Samuel Bolduc Dec 03 '13 at 15:39
  • @SamuelBolduc The first method uses an array's method on the array-like list; the second converts the list into an array, then uses a shortcut method (which itself invokes an array method). There's no danger of false positives. – Barney Dec 03 '13 at 15:47