Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery - grabbing an integer from an element's id

From the following markup.

<div id="my-div">
    <a href="#" id="link-1">Somewhere</a>
    <a href="#" id="link-2">Somewhere else</a>
</div>

What are some options, using jQuery selectors and JavaScript for grabbing the integer in the ids?

For example.

$("#my-div a").click(function(){
    $(this).id // ... somehow grab n from "link-n"        
    alert(n);
});
like image 334
jerome Avatar asked Jan 08 '10 19:01

jerome


2 Answers

You could try:

var n = $(this).attr('id').match(/link-(\d+)/)[1];

This fetches the id attribute, matches against the pattern link-(\d+) (which means link- followed by one or more digits), and then extracts the first subexpression match (the part in the parentheses \d+), which should be the number you are looking for.

If you need to work with n as an integer instead of a string, you should should use parseInt, making sure to specify base 10:

var n = parseInt($(this).attr('id').match(/link-(\d+)/)[1], 10);

If your id attributes are not guaranteed to begin with link- followed by one or more digits, and you would like to catch this case instead of throwing an error, you should check the return value of match:

var match = $(this).attr('id').match(/link-(\d+)/);
if (match) {
    var n = parseInt(match[1], 10);
    alert(n);
} else {
    // do something else if they don't match
}
like image 153
Brian Campbell Avatar answered Nov 01 '22 04:11

Brian Campbell


$(this).attr('id').replace('link-','')

like image 23
Antony Hatchkins Avatar answered Nov 01 '22 04:11

Antony Hatchkins