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?
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.
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.
$(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.
var id = $("div").attr('id').replace(/button/, '');
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With