121

I have a question. I have elements something like this:

<a> element with id = someGenerated Some:Same:0:name

<a> element with id = someGenerated Some:Same:0:surname

<a> element with id = someGenerated Some:Same:1:name

<a> element with id = someGenerated Some:Same:1:surname

I need CSS selector to get names. The problem is that I don't know how to get it. I tried a[id*='Some:Same'] - it returned all <a> elements. After I can get elements which id ends with name. But I don't like this idea. I think that it can be done with some other selector.

andyb
  • 43,435
  • 12
  • 121
  • 150
TarasLviv
  • 1,411
  • 3
  • 12
  • 17

3 Answers3

180

Try this:

a[id*='Some:Same'][id$='name']

This will get you all a elements with id containing

Some:Same

and have the id ending in

name

CosminO
  • 5,018
  • 6
  • 28
  • 50
  • Well, id* didn't work for me and it said can't be evaluated to a web element. I used it to find iframe which has id like `` name. `//driver.findElements(By.xpath("//iframe[contains(@id*,'FrameID')]")).size();` where FrameID is beginning part. Anyways, `//a[contains(@id,'Some:Same') and contains(@id,'name')]` did the trick for me. So +1 to you mate. – anujin Oct 12 '13 at 04:11
  • 2
    You should remove the XPath selector from this answer, it's not adding anything and is only muddying the waters – Liam May 02 '14 at 09:25
  • 1
    @CosminO Do you need the `*` next to `id`? – cokedude Sep 25 '18 at 21:17
  • @cokedude the *= operator means that it must contain at least the value after the operator. It works in conjunction with the second condition that it must end with something else by using the operator $= See this for an in depth explanation https://www.w3schools.com/css/css_attribute_selectors.asp Short answer. The * is not next to id, it is next to = and it forms an operator with special meaning – CosminO Oct 03 '18 at 10:00
55
<div id='element_123_wrapper_text'>My sample DIV</div>

The Operator ^ - Match elements that starts with given value

div[id^="element_123"] {

}

The Operator $ - Match elements that ends with given value

div[id$="wrapper_text"] {

}

The Operator * - Match elements that have an attribute containing a given value

div[id*="123_wrapper"] {

}
mybrave
  • 1,662
  • 3
  • 20
  • 37
Edicarlos Lopes
  • 971
  • 10
  • 5
7

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

LeBen
  • 1,884
  • 12
  • 21