Andersson
Andersson

Reputation: 52665

How to click on a parent element

I have following HTML element (hidden radio button)

<label class="btn btn-primary">
     <input class="type_radio" name="type" id="optionWIDGET" autocomplete="off" value="WIDGET" type="radio">
     WIDGET
</label>

Target element is a <label> and I can use

driver.find_element_by_xpath('//label[@class="btn btn-primary"]').click()

But the problem is that there are few more similar elements with attribute class="btn btn-primary". So I want to make my xpath more specific by adding reference to child <input> element.

However,

driver.find_element_by_xpath('//label[@class="btn btn-primary"]/input[@id="optionWIDGET"]').click()

will click on <input>, but not on <label> element.

The question is: how to click on parent element if I know the locator of child element?

PS. Searching elementS by same class name and then clicking on element from list by its index is not acceptable

Upvotes: 2

Views: 4001

Answers (2)

JRodDynamite
JRodDynamite

Reputation: 12613

You can simply use the parent axis. Try the following XPath.

'//input[@id="optionWIDGET"]/parent::label'

Upvotes: 3

gtlambert
gtlambert

Reputation: 11961

You can use the following XPath to click on the parent label of the input:

//input[@id="optionWIDGET"]/parent::label

So you can use:

driver.find_element_by_xpath('//input[@id="optionWIDGET"]/parent::label').click()

Note that since the id attribute is unique on a webpage, you can select the desired input element without using label[@class="btn btn-primary"] at the beginning of your XPath.

Upvotes: 2

Related Questions