Lutz
Lutz

Reputation: 23

switch case statement based one of many classes

I'm trying to implement a switch case statement like this:

switch (active.attr('class')){
    case "video": ...

        case "slideshow": ...
...

The problem is, that "video" and "slideshow" each are one of three classes the div I'm trying to target has, therefor it doesn't match the case...

How would I basically say "video is a part of attr('class')" ?

Thanks, Lutz

Upvotes: 2

Views: 3636

Answers (4)

Siewers
Siewers

Reputation: 22836

You could perhaps try and split the string. From the top of my head:

var classes = active.attr('class').split(' ');
foreach(var c in classes) {
    switch(c) {
        case 'video'
        ...
        case 'slideshow'
        ...
    }
}

Just an idea. The above answers might do the same in other ways :)

Edit:

You could also use jQuery .each() like this:

classes.each(function(c) {
    switch(c) {
        case 'video'
        ...
        case 'slideshow'
        ...
    }
}

Upvotes: 4

jAndy
jAndy

Reputation: 236092

It looks like you're using jQuery, which offers two methods for that:

So you can either call:

if( active.hasClass('video') ) { }

or

if( active.is('.video') ) { }

Notice that .is() requires a more specific pattern with the leading . but it you can determine lots of other things too like .is('div') etc.

Upvotes: 4

tvanfosson
tvanfosson

Reputation: 532595

Use if and the hasClass method:

if (active.hasClass('video')) {
}
else if {active.hasClass('slideshow')) {
}

If you need to do both (fall-through on the switch), remove the else so the if statements are independent.

Upvotes: 1

TNC
TNC

Reputation: 5386

You can use hasClass

See this related post. I think it does what you're looking to do.

Upvotes: 2

Related Questions