views:

220

answers:

5

how can i get the number from a div tag's id?

example:

<div id="button1"></div>

how can i get the 1 and store it in a variable?

+1  A: 
var id = $("div").attr('id').replace(/button/, '');
Konrad Garus
+3  A: 

Your "id" values cannot be purely numeric; they need to start with a letter or "_" like an identifier. Once you've got a number in your "id" value like that, you would just use the jQuery attr() function to get the id:

 var theId = parseInt($('div.whatever').attr('id').replace(/[^\d]/g, ''), 10);
Pointy
may I ask u a question. what does /[^\d]/g mean?
sunglim
It's a regular expression. It matches any non-digit with this part: "[^\d]". The "g" at the end tells Javascript to repeat the "replace" operation for all non-digits it finds in the string.
Pointy
A: 
// replace all non-digits with nothing
alert($('div').attr("id").replace(/\D/g,''));

If you like, you can just grab the numbers at the end:

// <div id="_34_foo_555"></div>
alert($('div').attr("id").match(/\d+$/));
// alerts "555"
karim79
A: 

If button is a constant prefix, you can do this:

var number = parseInt(element.id.match(/^button(\d+)$/)[1], 10);
Gumbo
A: 

You should get in the habit of using delimiters in your attribute names (ie, button-1, button_1). One of the advantages, of many, is that it makes it easier to extract a number, or some other information, from the field (ie, by splitting the string at '-').

John Himmelman