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.

6
  • 2
    Question is NOT a duplicate of stackoverflow.com/questions/1227286/… Commented Jun 12, 2014 at 14:17
  • Why you using int dataType inside for loop ... do you think Is it right in jQuery Commented Jun 12, 2014 at 14:22
  • @kamesh what do you mean? Commented Jun 12, 2014 at 14:28
  • @AlexandruSeverin: Re kamesh's comment, you have for(int i =0... in your question. As this is JS, that should be var (or let in ES6). Commented Jun 12, 2014 at 14:30
  • @T.j.Crowder thank that what i try to say Commented Jun 12, 2014 at 14:32

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

8 Comments

Beware using \b with classes, there are several characters that are valid in class names that \b treats as word boundaries, - being the most problematic.
@T.J.Crowder How's that? Better now?
className.match(/(b-\d+)/g)[0].substr(2)
@pawel: That fails to account for class="somethingunrelatedb-32"
Oh, that data-* attribute is even better and solves a lot of problems.
|
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.

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.