Wildcards in jQuery selectors
Asked Answered
T

6

736

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>
Tactless answered 21/3, 2011 at 10:34 Comment(4)
This is a question about jQuery (or more exactly the Sizzle engine).Purveyor
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).Openandshut
possible duplicate of JQuery selector regular expressionsGauzy
Also, an important thing to note is that $("[id*=jander]") would select all elements with an ID containing the string jander.Gourde
A
1394

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

Anagrammatize answered 21/3, 2011 at 10:35 Comment(1)
The docs give this example: $('input[name^="news"]').val('news here!')Abettor
S
135

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.

Spermicide answered 2/1, 2013 at 16:8 Comment(0)
J
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?

Jarietta answered 21/3, 2011 at 10:38 Comment(1)
Thanks for the classes hint, that brought me to the right direction!Magyar
F
38

for classes you can use:

div[class^="jander"]
Finicking answered 26/6, 2012 at 17:51 Comment(0)
W
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>
Wester answered 17/6, 2013 at 23:2 Comment(0)
R
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.

Retrusion answered 29/8, 2013 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.