Reputation: 17467
I know my selector will have a class of level-1, level-2, level-3
I want to set the level based on this but my way feels a bit clunky? Is there a neater way to do this
if ( $level.hasClass('level-2')) {
$levelValue= "level2";
}
if( $level.hasClass('level-3')) {
$levelValue = "level3";
}
if ( $level.hasClass('level-4')) {
$levelValue= "level4";
}
edit: sorry my mistake
Upvotes: 1
Views: 52
Reputation: 15558
Use this:
if($level.is('.level-2, .level-3, .level-4')){
$level = "level2";
}
This uses jQuery's .is()
function and checks whether $level
has any of the classes.
Update: Try using this:
if($level.is('[class^="level"]')){
$levelValue = $level.attr('class').match(/level-[0-9]*/); // e.g. 'level-2'
}
Here it is working: http://jsfiddle.net/rE3bL/1/
Upvotes: 2
Reputation: 1223
what is $level? a div? if you want to set $level to "level1", "level2" and "level3" (not "level2" every time like in your code), you can use the data attr:
<div class="level1" data-level="1">
<div class="level2" data-level="2">
<div class="level3" data-level="3">
and your js is like:
$level = $level.data("level") //will return "1","2" or "3"
Upvotes: 0
Reputation: 30446
Are there style rules associated with each level? If it's just data the I'd use a data attribute like data-level='2'
then you can access this by using this jQuery function: $level.data('level')
Upvotes: 0