1

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

1
  • Are you really trying to set level to level2 for all of the classes?? It looks like you made a mistake but I could be wrong if thats what you intended.... Also in your question you say it will have class level-1 to level-3 but in the code it does 2-4. Which do you need? Commented Oct 9, 2013 at 14:21

3 Answers 3

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

lovely - thanks very much, I need to get better at regular expressions. Though it needs the wildcard in my code class*="level"
0

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')

Comments

0

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"

1 Comment

this would definately work but is a drupal menu and I cant access the data attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.