Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get number from id

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?

like image 209
john morris Avatar asked Mar 11 '10 19:03

john morris


People also ask

How to get the value of an id in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.

What is id selector in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What is this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.


2 Answers

var id = $("div").attr('id').replace(/button/, '');
like image 187
Konrad Garus Avatar answered Oct 23 '22 14:10

Konrad Garus


Your "id" values cannot be purely numeric; they need to start with a letter or "_" like an identifier. (Note: that's not true in HTML5 documents.) 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);
like image 13
Pointy Avatar answered Oct 23 '22 14:10

Pointy