mattman88
mattman88

Reputation: 495

How to use xpath toI find a label attribute in an arbitrary place

I need to be able to find a label attribute using xpath when the label is buried arbitrarily deep in the HTML. I need to be able to just say something like //*[label] and have it find the first label in the HTML, but it won't. Is there any way to do this? Hopefully my questions was descriptive enough. Thanks.

Upvotes: 3

Views: 19579

Answers (3)

Alberto R.
Alberto R.

Reputation: 170

If your label is associated with an input I would suggest using "for" attribute to search it.

e.g : //label[@for='input_id']

I would discourage the user of text label if you want only one element. Take in account also that label text can be changed often and they are language dependent.

Hope this helps

Upvotes: 5

har07
har07

Reputation: 89325

XPath expression to match any label in the document :

//label

XPath expression to match only the first label found :

(//label)[1]

Upvotes: 0

matthias_h
matthias_h

Reputation: 11416

Maybe a misunderstanding, but possibly an answer - in case it's about a <label>-element like e.g.

<label for="first">First Name</label>

the XPath //label/text() gets the value - First Name - , the XPath //label the whole label-element <label for="first">First Name</label>. In case you mean something else, please provide more details in your question.

Upvotes: 1

Related Questions