niemeczek
niemeczek

Reputation: 35

XPath Cannot locate element using text()

following code:

<label>
<input class="class1" type="checkbox" checked="checked"/>
                First text             
</label>
<label>
<input class="class2" type="checkbox" checked="checked"/>
                Second text             
</label>
<label>
<input class="class3" type="checkbox" checked="checked"/>
                Third text             
</label>

What I want to do is to get specific label element by containing text. I was trying:

//label[text()='First text']

and

//label[contains(text(),'First text')]

but it doesnt work.

Please, advise!

Thanks! :)

Upvotes: 1

Views: 711

Answers (1)

Tomalak
Tomalak

Reputation: 338406

//label[text()[contains(., 'First text')]]

Your attempt

//label[contains(text(),'First text')]

does not work because the <label> in

<label>[
]<input class="class1" type="checkbox" checked="checked"/>[
                First text             
]</label>

has two text nodes: an empty one containing nothing but a line break, right before the input, and a non-empty one after the <input>. I've outlined them with square brackets above.

  • A call like contains(node-set, string) forces a conversion of the first argument to contains to string.
  • Converting a node-set to string gives you the text content of the first node of the set. (Try it out, string(label) will give you 'First text' with a bunch of whitespace, no matter how many labels there are.)
  • And in your case, that's the empty text node, so contains(text(),'First text') will never succeed.

Therefore you must test the text nodes individually, and that's done by nesting predicates like shown above.

Upvotes: 2

Related Questions