1

I've got an element like this:

<ul class="MainMenu_SubMenu m m0 mid157">

I need to get the mid157 and use that 157 for a variable for something else, i.e:

$('SomeOtherElement157')

So my question is how do get the class name as a variable and then strip all but the number? The classes are generated so some have more and some have less but they will all have that mid...

5 Answers 5

5
var className = $('ul').attr('class'),
    midNum = /\bmid(\S+)/.exec(className)[1],
    selector = 'SomeOtherElement' + midNum;

$(selector);

Works for all of the following:

<ul class="MainMenu_SubMenu m m0 mid157"></ul>
<ul class="mid158"></ul>
<ul class="mid159 MainMenu_SubMenu m m0"></ul>
<ul class="MainMenu_SubMenu mid160 m m0"></ul>

Demo: http://jsfiddle.net/mattball/P3G8H/

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

3 Comments

A ul element with the particular element is a element in the page and may not be the only ul tag. We should rather use the class name or ul + class name combined.
@Rohan you are 100% correct, but the OP did not provide much information to go on.
I did end up using more specific selectors but your solution was perfect for what I needed! Thank you very much!
0

You can use grep:

var classes=$("div").attr("class").split(" ");

var matches = jQuery.grep(classes, function(n, i){
  return n.indexOf("mid")===0;
});

if(matches[0]){
    var number=matches[0].substring(3);

    // do something with that number 
}

Comments

0
var patt1   = /mid(\d+)/,
    matches = $('ul').attr('class').match(patt1);

if (matches != undefined && matches[1] != undefined) {
    $('SomeOtherElement'+matches[1]);        
} else {
    alert("No matches.");   
}

Comments

0
var id = $("div").attr("class").match(/mid([\d]+)/gi)[0].replace("mid", "SomethingElse");

alert(id);

http://jsfiddle.net/bkSFf/

Comments

0
var nums = 
    document.getElementsByTagName('ul')[0]
                .className.match(/.*mid(\d*)/)[1];

$('selector' + nums);

1 Comment

Wont this return an error if no class 'mid(\d*)' is found? You would be trying to call [1] on an undefined/null object.

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.