43

I have the following XPath to match attributes of the class span:

//span[@class='amount']

I want to match all elements that have the class attribute of "amount" but also may have other classes as well. I thought I could do this:

//span[@class='*amount*'] 

but that doesn't work...how can I do this?

0

2 Answers 2

50

Use the following expression:

//span[contains(concat(' ', @class, ' '), ' amount ')]

You could use contains on its own, but that would also match classes like someamount. Test the above expression on the following input:

<root>
  <span class="test amount blah"/>
  <span class="amount test"/>
  <span class="test amount"/>
  <span class="amount"/>
  <span class="someamount"/>
</root>

It will select the first four span elements, but not the last one.

Sign up to request clarification or add additional context in comments.

2 Comments

If suppose, I want to retrieve the text content inside the span tag then what will be the code. I have stored the result in nodelist and tried to print the content using nodelist.item(0).getFirstChild().getNodeValue(). But this doesn't return anything. Please help me out.
Interesting how a total of four (2 x 2) blanks are needed.
25

You need to use contains method. See How to use XPath contains() here?

//span[contains(@class,'amount')]

1 Comment

Unfortunately, that will also match class="lookamountain". @lwburk has the right answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.