SamotnyPocitac
SamotnyPocitac

Reputation: 402

jQuery selector all ids that are integer

How do I select all ids which are the integers.

for example

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>

somdething [id^="integer"]?

I know how to select ids that has similar name starting:

[id^="similar_"]

Upvotes: 4

Views: 893

Answers (4)

kayen
kayen

Reputation: 4868

$('div').filter(function(){ return this.id.match(/^\d+$/) })

Upvotes: 4

Fiddle Demo

$('[id]').filter(function () {
    return !isNaN((this.id)[0]) && this.id.indexOf('.') === -1;
}).css('color', 'red');

Has Attribute Selector [name]

.filter()

isNaN()

Upvotes: 4

Johan
Johan

Reputation: 35194

No need to use regex here...

$('div').filter(function(){ 
    return this.id && !isNaN(this.id) && this.id % 1===0;
});

isNaN(123)     // false
isNaN('123')   // false
isNaN('foo')   // true
isNaN('10px')  // true

Upvotes: 3

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You can use filter(). The equivalent of [id^=integer] would be :

$('div').filter(function(){
    return this.id.match(/^\d/);
})

Only integer would be :

$('div').filter(function(){
    return this.id.match(/^\d+$/);
})

Upvotes: 7

Related Questions