Wildcards in jQuery selectors

JqueryJquery SelectorsSizzle

Jquery Problem Overview


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>

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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.

Solution 3 - Jquery

Try the jQuery starts-with > selector, '^=', eg

[id^="jander"]

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

Solution 4 - Jquery

for classes you can use:

div[class^="jander"]

Solution 5 - Jquery

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>

Solution 6 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionziiwebView Question on Stackoverflow
Solution 1 - JquerynicoView Answer on Stackoverflow
Solution 2 - JqueryMartijn SmidtView Answer on Stackoverflow
Solution 3 - JqueryGoatInTheMachineView Answer on Stackoverflow
Solution 4 - Jqueryl3thalView Answer on Stackoverflow
Solution 5 - JqueryPJ BrunetView Answer on Stackoverflow
Solution 6 - JqueryeduardView Answer on Stackoverflow