34

I am trying to write an xpath expression that selects all div tags that have an attribute id that start with CompanyCalendar. Below is a snippet of the HTML that I am looking at:

<td class="some class" align="center" onclick="Calendar_DayClicked(this,'EventCont','Event');">
        <span class="Text"></span>
        <div id="CompanyCalendar02.21" class="Pop CalendarClick" style="right: 200px; top: 235px;"></div>

There are multiple divs that have an id like CompanyCalendar02.21 but for each new month in the calendar, they change the id. For example, the next month would be CompanyCalendar02.22. I would like to be able to select all of the divs that are equal to CompanyCalendar*

I am rather new at this so I was using some example off the net to try and get my xpath expression to work but to no avail. Any help would be greatly appreciated.

Marek
  • 863
  • 4
  • 12
  • 19
  • possible duplicate of [Selecting elements whose attribute begins with something in XPath](http://stackoverflow.com/questions/3301898/selecting-elements-whose-attribute-begins-with-something-in-xpath) – OtherDevOpsGene Oct 14 '14 at 17:18

2 Answers2

72

I am trying to write an xpath expression that selects all div tags that have an attribute id that start with CompanyCalendar.

The following expression is perhaps what you are looking for:

//div[starts-with(@id,'CompanyCalendar')]

What it does, in plain English, is

Return all div elements in the XML document that have an attribute id whose attribute value starts with "CompanyCalendar".

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
  • That is exactly what I was looking for. I had the @id in the wrong place in my expression (before the starts-with) so it didn't work at all. Thanks! – Marek Oct 14 '14 at 17:18
  • 1
    @user3420391 You are welcome. That is why you would have benefited from including your attempted solution in the question. Then, somebody could have explained what is wrong. – Mathias Müller Oct 14 '14 at 17:20
0

While checking in Browser console with the $x() call, it worked only after flipping the quotes - i.e. double quotes inside the Xpath starts-with() call.

$x('//div[starts-with(@id,"CompanyCalendar")]')
CodeYoga
  • 35
  • 5
  • I think this may be useful information, but make sure to separate 1) XPath rules and 2) effects coming from the environment you use XPath in, such as the JS console in the browser, in this case. XPath itself does not distinguish between single and double quotes, as long as they come in consistent sets. – Mathias Müller Feb 21 '23 at 11:00