10

Is there a way to select all id's with jQuery with a prefix "my" and a suffix "0-9". Something like these $("#my$1-4") or is it just possible with a loop ?

    <div id="my1"/>
    <div id="my2"/>
    <div id="my3"/>
    <div id="my4"/>
    <div id="my5"/>
MR.ABC
  • 4,712
  • 13
  • 44
  • 88
  • Do you need only **id** selector? Why not to use class, name or data selector. For last one see http://stackoverflow.com/questions/2891452/jquery-data-selector Also there are attributes selectors like this one http://api.jquery.com/attribute-contains-prefix-selector/ – m03geek Jun 23 '12 at 21:44

3 Answers3

27

First thoughts, which seems to work well:

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

JS Fiddle demo.

The above selects all div elements whose id starts with the value my, and then filters the returned elements to those whose id also ends with numeric characters.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
4

The prefix part is easily achievable with an attribute starts-with selector:

$("div[id^=my]");

But there is no selector that will allow you to specify a range of characters, so a loop will have to be involved. I would suggest filter:

$("div").filter(function () {
    return /^my\d$/.test(this.id);
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

Assuming you don't have millions of elements that start with "my", you could do:

$('[id^=my]').filter(function() { return this.id.matches(/\d/) && this.id.length == 3 })

This grabs all elements that have an id starting with "my", contain a number, and are only 3 characters long (so "my54" will not match but "my6" will)

Kyle Macey
  • 8,074
  • 2
  • 38
  • 78