0

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
3
  • 1
    Can't help wondering why do you need to use classes to store what looks like semantic data. Commented 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 ;) Commented Jan 31, 2013 at 21:00
  • 1
    This is an XY problem. Commented Jan 31, 2013 at 21:14

2 Answers 2

3

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:

[1] http://tutorialzine.com/2010/11/jquery-data-method/

answered Jan 31, 2013 at 21:04
Sign up to request clarification or add additional context in comments.

4 Comments

This is the right tool for the job.
data attributes have been around for awhile actually caniuse.com/dataset
@wirey, data attributes have been supported for a while, but they weren't standardized until the HTML5 spec, which would require the HTML5 doctype.
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)
2
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

11 Comments

thanks a lot, it worked! will accept your answer as soon as I can
btw, if you want, can you exlain the (/\b\d+\b/) part? I don't see any logic in it
@Axel the class name restriction you are referencing does not exist in the current HTML spec
@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)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.