jQuery or CSS selector to select all IDs that start with some string
Solution 1
Normally you would select IDs using the ID selector #
, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):
div[id^="player_"]
If you are able to modify that HTML, however, you should add a class to your player div
s then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.
Solution 2
try this:
$('div[id^="player_"]')
Solution 3
You can use meta characters like *
(http://api.jquery.com/category/selectors/).
So I think you just can use $('#player_*')
.
In your case you could also try the "Attribute starts with" selector:
http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')
Solution 4
$('div[id ^= "player_"]');
This worked for me..select all Div starts with "players_" keyword and display it.
Related videos on Youtube
matt
Updated on May 21, 2020Comments
-
matt almost 4 years
How can I select all elements whose
id
starts with "player_"?I have multiple elements like this:
<div id="player_290x3dfda">text</div>
Every
id
has a unique stamp on it. How can I select all those elements, either with jQuery or with pure CSS?-
Mahima about 13 years
-
-
Jim over 10 yearsIs this selector in CSS works on older browsers like ie8 and ie9, and if not what the alternative?
-
doub1ejack about 10 yearsIt's very compatible - check out quirksmode: quirksmode.org/css/selectors/#link3
-
Konrad Viltersten almost 10 yearsActually I believe that you can't use $('#prefix*'). At least I don't get it to work...
-
rept over 9 yearsThis doesn't work for me (in Chrome).
-
Vinicius Monteiro over 8 yearsWell I think you don't understand what the documentation says: To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?@[\]^`{|}~
) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector$("#foo\\.bar")
-
KWallace about 7 yearsThis should be the answer. It shows how to actually implement the solution in code. Thanks, Prakash!
-
And Wan almost 7 yearswhat if you don't know the type of html element? like it could be an input, or select, etc.
-
BoltClock almost 7 years@And Wan: Then leave out the type selector. It's not required.
-
Raqem over 2 yearsUsing a class for functionality is a bad practice! CSS is for styling! What if the class names changed because new styles were implemented? Then all of your functions would break!
-
BoltClock over 2 years