57

I have some elements generated with PHP and I would like to know if it is possible to select an element with an incomplete id, example:

<div class="1" id="as_1"> ... </div>
<div class="2" id="bs_1"> ... </div>

<div class="1" id="as_2"> ... </div>
<div class="2" id="bs_2"> ... </div>

The class is being used to things they have in common, but now I need to select them individually but I don't know the entire id name.

Can I use something like:

#as_{ ... }
#bs_{ ... }
isherwood
  • 58,414
  • 16
  • 114
  • 157
Fernando Andrade
  • 795
  • 1
  • 7
  • 19
  • Possible duplicate of [CSS selector (id contains part of text)](http://stackoverflow.com/questions/12155833/css-selector-id-contains-part-of-text) – Tony L. Aug 19 '16 at 20:07

2 Answers2

95

Not with ID selectors since they require complete ID names, but with substring attribute selectors:

div[id^="as_"]
div[id^="bs_"]

But since your elements have a class attribute anyway, why not add a common class to each group of elements and select by that class to make things simpler? You should be able to determine the grouping class using PHP as you do to generate the IDs.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • This is a good way to block certain advertisements that use random numbers for the div ids. – PJ Brunet Mar 01 '17 at 22:08
  • 3
    The answer implies this but I think this should be mentioned directly: `[id^="as_"]` DOES NOT have the same specificity as `#as_1` so this approach cannot be used to override id based styles – mzrnsh Jun 03 '17 at 23:11
  • 2
    @mizurnix: [That's right.](https://stackoverflow.com/questions/32868028/is-an-attribute-selector-for-the-id-attribute-less-specific-than-an-id-selector/32868338#32868338) – BoltClock Jun 04 '17 at 03:14
1

Not sure if an exact a match to this question but we're using CodeceptJs and for that we have these two equivalent pieces:

myLocator: {

// xpath: "//*[contains(@data-testid, 'drawer')]",
css: '[data-testid*="drawer"]',
},

So using data-testid*= for css instead of contains for xpath so as to match against an element which has its data-testid named something like drawer-{something_dynamic_appended}.

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81