1

Lets say I have this in my html:

<div id="myDiv" class="a b-32"/>

I'm trying to get the index of 'b' class (in my example '32')

The only way I know how to do it is by:

var index;
var myDiv = $("#myDiv").attr("class");
var classes = myDiv.split(' ');
for(var i=0; i<classes.size(); i++){
    if(classes[i].matches((b-)+[\d]*) ){
        index = classes[i].replace("b-","");
    }
}
alert(index);

Is there any solution that doesn't imply iterating all the classes manually? Because my solution seems dull. Surely there must be a better way, I just can't find it.

Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71

2 Answers2

4

Y'know, for all that people claim jQuery makes it so you have to write less code, Vanilla JS is surprisingly good at one-liners :p

alert((document.getElementById('myDiv').className
                                         .match(/(?:^| )b-(\d+)/) || [0,0])[1]);

(Whitespace added for readability)

Returns 0 in the event where myDiv doesn't have a b-number class.

EDIT: As @A.Wolff pointed out in a comment on your question, you may wish to consider this:

<div id="myDiv" class="a" data-b="32"></div>

Then you can get:

alert(document.getElementById('myDiv').getAttribute("data-b"));
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

A regular expression can help:

var index;
var myDivClasses = $("#myDiv").attr("class");
var cls = myDivClasses.match(/(?:^| )b-(\d+)(?:$| )/);
if (cls) {
    index = cls[1];
}

(Use parseInt if you want it as a number.)

That looks for b-### where ### is one or more digits, with either whitespace or a boundary (start of string, end of string) on either side, and extracts the digits.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875