Possible Duplicate:
Javascript / Jquery - Get number from string
Using
var id = $(this).attr("class");
I get all the classes of the clicked link, var id returns 4 classes:
button_red 501 ajax-call class2
How do I extract the class '501' and put it in an var like var id_numeric = 501 ?
Thanks for your advice
asked Jan 31, 2013 at 20:55
Maarten Hartman
1,6296 gold badges27 silver badges45 bronze badges
-
1Can't help wondering why do you need to use classes to store what looks like semantic data.raina77ow– raina77ow2013年01月31日 20:58:38 +00:00Commented Jan 31, 2013 at 20:58
-
usually I would store it in the ID, in this case the ID is already taken by something else (drupal ajax link). I understand you're wondering ;)Maarten Hartman– Maarten Hartman2013年01月31日 21:00:31 +00:00Commented Jan 31, 2013 at 21:00
-
1This is an XY problem.zzzzBov– zzzzBov2013年01月31日 21:14:00 +00:00Commented Jan 31, 2013 at 21:14
2 Answers 2
Assuming you are using an HTML5 doctype, you could probably use a data- attribute rather than a CSS class. For example:
data-id="501"
Then either
var id = $(this).attr("data-id");
or
var id = $(this).data("id"); //[1]
would work.
Reference:
answered Jan 31, 2013 at 21:04
Tieson T.
21.2k6 gold badges83 silver badges99 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
zzzzBov
This is the right tool for the job.
wirey00
data attributes have been around for awhile actually caniuse.com/dataset
zzzzBov
@wirey, data attributes have been supported for a while, but they weren't standardized until the HTML5 spec, which would require the HTML5 doctype.
Maarten Hartman
Thanks to you too Tieson, I will remember this for the future. I'm using drupal 7 ajax links, therefore I can't use it yet (done some googling)
var numericClassIdMatches = $(this).attr('class').match(/\b\d+\b/);
In the above case, 501 would be numericClassIdMatches[0]
answered Jan 31, 2013 at 20:57
Explosion Pills
193k56 gold badges341 silver badges417 bronze badges
11 Comments
Maarten Hartman
thanks a lot, it worked! will accept your answer as soon as I can
Maarten Hartman
btw, if you want, can you exlain the (/\b\d+\b/) part? I don't see any logic in it
Tieson T.
@MaartenHartman regular-expressions.info/reference.html
Explosion Pills
@Axel the class name restriction you are referencing does not exist in the current HTML spec
Explosion Pills
@MaartenHartman because look at how relatively complex it was to get the ID data you were looking for!
$(this).attr('class').match(/\b\d+\b/)[0]; vs. $(this).data('id'). Also, classes may be manipulated by other means ($(this).removeClass() will remove the ID class as well as the styling classes) |
lang-js