Damn Vegetables
Damn Vegetables

Reputation: 12474

XPath contains whole word only

I saw the existing question with the same title but that was a different question.

Let's say that I want to find elements that has "conGraph" in the class. I have tried

//div[contains(@class,'conGraph')]

It correctly got

<div class='conGraph mr'>

but it also falsely got

<div class='conGraph_wrap'>

which is not the same class at all. For this case only, I could use 'conGraph ' and get away with it, but I would like to know the general solution for future use.

In short, I want to get elements whose class contains "word" like "word", "word word2" or "word3 word", etc, but not like "words" or "fake_word" or "sword". Is that possible?

Upvotes: 1

Views: 664

Answers (1)

E.Wiest
E.Wiest

Reputation: 5915

One option could be to use 4 conditions (exact term + 3 contains function with whitespace support) :

For the first condition, you search the exact term in the attribute content. For the second, the third and the fourth you specify all the whitespace variants.

Data :

<div class='word'></div>
<div class='word word2'></div>
<div class='word word3'></div>
<div class='swords word'></div>
<div class='swords word words'></div>
<div class='words'></div>
<div class='fake_word'></div>
<div class='sword'></div>

XPath :

//div[@class="word" or contains(@class,"word ") or contains(@class," word") or contains(@class," word ")]

Output :

<div class='word'></div>
<div class='word word2'></div>
<div class='word word3'></div>
<div class='swords word'></div>
<div class='swords word words'></div>

Upvotes: 2

Related Questions