If I have an unknown amount of identifiers sharing a specific naming-scheme, is there a way to grab them all at once using jQuery?
// These are the IDs I'd like to select
#instance1
#instance2
#instance3
#instance4
// What do I need to add or how do I need to modify this jQuery selector in order to select all the IDs above?
("#instanceWILDCARD").click(function(){}
If you really want to match classes, not ids, the syntax is a bit more involved, since class can have multiple values.
Use the carrot.
jsFiddle example
The attribute starts-with selector (
'^=
) will work for your IDs, like this:However, consider giving your elements a common class, for instance (I crack myself up)
.instance
, and use that selector: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:
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!
or
Oh yeah, one more thing... you can chain it too. :)
Enjoy!
No need for additional expr or anything fancy if you have jQuery
As noted: https://stackoverflow.com/a/2220874/2845401
We can do it this way: