728

I'm trying to use a wildcard to get the id of all the elements whose id begin with "jander". I tried $('#jander*'), $('#jander%') but it doesn't work..

I know I can use classes of the elements to solve it, but it is also possible using wildcards??

<script type="text/javascript">

  var prueba = [];

  $('#jander').each(function () {
    prueba.push($(this).attr('id'));
  });

  alert(prueba);


});

</script>

<div id="jander1"></div>
<div id="jander2"></div>
Mechlar
  • 4,946
  • 12
  • 58
  • 83
tirenweb
  • 30,963
  • 73
  • 183
  • 303
  • 2
    This is a question about jQuery (or more exactly the Sizzle engine). – Peter Örneholm Mar 21 '11 at 10:37
  • 1
    Just a note: It would be much faster to do it with classes as jQuery or Sizzle can make use of browser functions (should not make much of a difference for modern browsers though). – Felix Kling Mar 21 '11 at 10:47
  • 4
    possible duplicate of [JQuery selector regular expressions](http://stackoverflow.com/questions/190253/jquery-selector-regular-expressions) – Robert MacLean Aug 31 '11 at 09:39
  • 8
    Also, an important thing to note is that `$("[id*=jander]")` would select all elements with an ID containing the string jander. – Gabriel Ryan Nahmias Jul 08 '12 at 11:03

6 Answers6

1386

To get all the elements starting with "jander" you should use:

$("[id^=jander]")

To get those that end with "jander"

$("[id$=jander]")

See also the JQuery documentation

nico
  • 50,859
  • 17
  • 87
  • 112
133

Since the title suggests wildcard you could also use this:

$(document).ready(function(){
  console.log($('[id*=ander]'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jander1"></div>
<div id="jander2"></div>

This will select the given string anywhere in the id.

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Martijn Smidt
  • 1,604
  • 1
  • 10
  • 10
42

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
GoatInTheMachine
  • 3,583
  • 3
  • 25
  • 35
38

for classes you can use:

div[class^="jander"]
joshuahedlund
  • 1,722
  • 2
  • 20
  • 25
l3thal
  • 562
  • 6
  • 11
16

To get the id from the wildcard match:

$('[id^=pick_]').click(
  function(event) {

    // Do something with the id # here: 
    alert('Picked: '+ event.target.id.slice(5));

  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pick_1">moo1</div>
<div id="pick_2">moo2</div>
<div id="pick_3">moo3</div>
Ajay2707
  • 5,690
  • 6
  • 40
  • 58
PJ Brunet
  • 3,615
  • 40
  • 37
12

When you have a more complex id string the double quotes are mandatory.

For example if you have an id like this: id="2.2", the correct way to access it is: $('input[id="2.2"]')

As much as possible use the double quotes, for safety reasons.

Simon M
  • 2,931
  • 2
  • 22
  • 37
eduard
  • 121
  • 1
  • 2