[jquery] Wildcards in jQuery selectors

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>

This question is related to jquery jquery-selectors sizzle

The answer is


for classes you can use:

div[class^="jander"]

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.


Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

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


To get the id from the wildcard match:

_x000D_
_x000D_
$('[id^=pick_]').click(_x000D_
  function(event) {_x000D_
_x000D_
    // Do something with the id # here: _x000D_
    alert('Picked: '+ event.target.id.slice(5));_x000D_
_x000D_
  }_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="pick_1">moo1</div>_x000D_
<div id="pick_2">moo2</div>_x000D_
<div id="pick_3">moo3</div>
_x000D_
_x000D_
_x000D_


Since the title suggests wildcard you could also use this:

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

This will select the given string anywhere in the id.