JavaScript
Article

jQuery get numbers only from element id

By Sam Deering

Say we are storing item ids inside the element container id attributes and we simply want to extract the numbers from the id attribute string. You can get the number from any elements id tag by using a simple JavaScript regular expression replace statement.

$(this).attr('id').replace(/[^d]/g, '');

Before: container1
After: 1

Say the id tag contains both letters and numbers and we are interested in getting only the number from the div container id. This could be used for something like when you are trying to grab an id from a parent container element:

//elements... //a button...with a bound click event
//elements... //a button...with a bound click event
//elements... //a button...with a bound click event

So when we click any element we can grab it’s container id to use.

//gets the container id number only from element
function getIdNum(elem)
{
    if (elem.attr('id'))
    {
        return elem.attr('id').replace(/[^d]/g, '');
    }
    else
    {
        return elem.parents('.widget').attr('id').replace(/[^d]/g, '');
    }
}

//example call
var containerId = getIdNum($('some button'));

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.