I would like to locate this element,
<div class="item-price">$0.99</div>
using XPath which says select div
elements whose class
attribute equals "item-price"
and whose content contains a dollar sign ($
).
This XPath expression:
//div[contains(@class, 'item-price') and contains(., '$')]
Will match all div
elements of the item-price
class containing a '$'.
It's useful to use contains()
in the test on @class
if you want to match cases where there are multiple CSS styles specified in the @class
value.
Caution: For a more robust solution, apply the following technique to avoid unintended substring matches (item-price
matching, say, item-prices
):
//div[contains(concat(' ',@class,' '), ' item-price ') and contains(., '$')]
contains()
because it is very valuable. I like the conjunctive syntax used above a bit more. So I'm torn on which to select as the answer because both are correct.
Oct 22, 2013 at 14:08
As per the HTML:
<div class="item-price">$0.99</div>
There is:
item-price
$
sign.So, to locate this element with respect to the value of the class attribute i.e. item-price
and innerText content starting with a dollar sign ($
) you can use either of the following solutions:
Using starts-with()
:
//div[@class='item-price' and starts-with(., '$')]
Using contains()
:
//div[@class='item-price' and contains(., '$')]
@attributename
, you can use thecontains()
function on the content. Could you give us your best effort using those 2?//div[@class="item-price" and contains("$")]
but I'm unsure of how to make conjunctions. I've also seen//div[one][theother]
.contains()
? You're very close (contains(.,'$')
would do it)