Is there a wildcard selector for identifiers (id)? Is there a wildcard selector for identifiers (id)? jquery jquery

Is there a wildcard selector for identifiers (id)?


The attribute starts-with selector ('^=) will work for your IDs, like this:

$("[id^=instance]").click(function() {  //do stuff});

However, consider giving your elements a common class, for instance (I crack myself up) .instance, and use that selector:

$(".instance").click(function() {  //do stuff});


If you really want to match classes, not ids, the syntax is a bit more involved, since class can have multiple values.

// handle elements like <div class="someclass1"></div>$('[class^="someclass"]').click(function() {   // do stuff});// handle elements like <div class="foo someclass1"></div>$('[class*=" someclass"]').click(function() {   // do stuff});


I'm surprised no one has mentioned creating your own filter selector (by extending jQuery's Selector functionality). Here I've created a wildcard selectors I called "likeClass" and "likeId" that accepts any wildcard string and will find all elements that are a match (similar to Regex matching).

Code:

$.expr[':'].likeClass = function(match){      return $('[class*=" '+ match +'"]');};$.expr[':'].likeId = function(match){      return $('[id*=" '+ match +'"]');};

Example Usage:

Now let's say you had multiple div elements with similar names like .content-1, .content-2, .content-n... etc and you want to select them. Now it's cake!

$('div:likeClass(content-)'); // Returns all elements that have a similar Classname: content-*

or

$('div:likeClass(content-)'); // Returns all elements that have a similar ID: content-*

Oh yeah, one more thing... you can chain it too. :)

$('li:likeId(slider-content-)').hide().addClass('sliderBlock').first().fadeIn('fast');

Enjoy!