jQuery or CSS selector to select all IDs that start with some string

144,608

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 divs 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.

Share:
144,608

Related videos on Youtube

matt
Author by

matt

Updated on May 21, 2020

Comments

  • matt
    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?

  • Jim
    Jim over 10 years
    Is this selector in CSS works on older browsers like ie8 and ie9, and if not what the alternative?
  • doub1ejack
    doub1ejack about 10 years
    It's very compatible - check out quirksmode: quirksmode.org/css/selectors/#link3
  • Konrad Viltersten
    Konrad Viltersten almost 10 years
    Actually I believe that you can't use $('#prefix*'). At least I don't get it to work...
  • rept
    rept over 9 years
    This doesn't work for me (in Chrome).
  • Vinicius Monteiro
    Vinicius Monteiro over 8 years
    Well 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
    KWallace about 7 years
    This should be the answer. It shows how to actually implement the solution in code. Thanks, Prakash!
  • And Wan
    And Wan almost 7 years
    what if you don't know the type of html element? like it could be an input, or select, etc.
  • BoltClock
    BoltClock almost 7 years
    @And Wan: Then leave out the type selector. It's not required.
  • Raqem
    Raqem over 2 years
    Using 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
    BoltClock over 2 years