user2952265
user2952265

Reputation: 1630

How to check for a class name if several classes are assignend?

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);
   }

Upvotes: 0

Views: 67

Answers (4)

Samuel Bolduc
Samuel Bolduc

Reputation: 19173

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.

Upvotes: 1

Barney
Barney

Reputation: 16456

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);
}

Upvotes: 1

Samuel
Samuel

Reputation: 2156

In jQuery:

$( "#mydiv" ).hasClass( "foo" )

Upvotes: 2

eRIZ
eRIZ

Reputation: 1507

classList is not currently wiredly available.

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

Upvotes: 1

Related Questions