0

I want to select second class value with jquery. For example;

<div class="mb-20"></div>

How can i get "20" value after from "mb-" ?

3
  • 1
    There is no "second" class value, that's a single className Commented Apr 4, 2015 at 1:06
  • 1
    If you want to target every element with a class that ends with 20, you can do $('[class$="20"]') Commented Apr 4, 2015 at 1:07
  • 2
    You'd be parsing the "20" from the string "mb-20". How you define your pattern for parsing the value is up to you. You can split the string at the "-" and take the second index, or the last index. You can replace "mb-" with nothing. You can take the substring starting at index 3. Etc. What you have is a string. What you want is part of that string. Identify the pattern which gives you that part, and implement that. Commented Apr 4, 2015 at 1:07

3 Answers 3

1

Here a sample of what you need, to illustrate i made this when you click the div.

// The selector just get all class starting with mb
$('[class^="mb"]').on('click', function() {
   alert($(this).attr('class').split('-')[1]);
});

And here is the FIDDLE

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

1 Comment

Thanks so much for your help. There is just a problem, when you add a more class, it taking it too; jsfiddle.net/hfezwfqj/1
0

If you have already selected the div you can iterate over its classes, and split each class on hyphen. Something like...

$.each($('div').attr('class').split(/s+/), function(idx, val) {
    var parts = val.split('-');
    var classBase = parts[0];
    var classModifier = parts.length > 1 ? parts[1] : null;

    if(classModifier !== null) alert("found class modifier" + classModifier);
});

Comments

0

If divs have more than one class, you can do this:

$('[class^="mb"]').on('click', function() {
     alert($(this).attr('class').split(' ')[0].split('-')[1]);
});

This will get first class of element first, second, split it with - and return the number.

Here is the updated Gonzalo Bahamondez's fiddle.

Comments

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.