Riaz Ladhani
Riaz Ladhani

Reputation: 4062

XPATH or CSS I I have a list of checkboxes in span tags. I am trying to select a particular checkbox

I have a list of checkboxes in the HTML span tag. In the span tag there is an input tag and a label tag. I would like to click the checkbox in the input tag which has the label text e.g. "Allow gender mismatch" In my XPATH I can get to the label tag but I do not know how to go up 1 so i can click on the input tag.

I would like some help in getting the XPATH or CSS locator for this please.

I cannot use id="gwt-uid-1204" as this is a dynamic value. It changes when you visit the page

My XPATH to get the label text is:

//div[@id="match_configuration_add_possible_tab_match_rules_fp_flags"]/span/label[contains(text(), "Allow gender mismatch")]

The HTML snippet is:

<div id="match_configuration_add_possible_tab_match_rules_fp_flags">
    <div class="gwt-Label matchruleheader">Gender and title flags</div>
    <span class="gwt-CheckBox" style="display: block;">
        <input id="gwt-uid-1204" type="checkbox" value="on" tabindex="0"/>
        <label for="gwt-uid-1204">Gender must be present in both names</label>
    </span>
    <span class="gwt-CheckBox" style="display: block;">
        <input id="gwt-uid-1205" type="checkbox" value="on" tabindex="0"/>
        <label for="gwt-uid-1205">Gender must be consistent in both names</label>
    </span>
    <span class="gwt-CheckBox" style="display: block;">
        <input id="gwt-uid-1206" type="checkbox" value="on" tabindex="0"/>
        <label for="gwt-uid-1206">Allow gender mismatch</label>
    </span>
    <span class="gwt-CheckBox" style="display: block;">
    <span class="gwt-CheckBox" style="display: block;">
    <span class="gwt-CheckBox" style="display: block;">
    -- More checkboxes
</div>

Thanks, Riaz

Upvotes: 1

Views: 627

Answers (2)

drkthng
drkthng

Reputation: 6909

you have at least two possibilities:

1) use xpaths ".." to go one element up

//div[@id="match_configuration_add_possible_tab_match_rules_fp_flags"]/span/label[contains(text(), "Allow gender mismatch")]/../input

2) use xpaths "preceding-sibling":

//div[@id="match_configuration_add_possible_tab_match_rules_fp_flags"]/span/label[contains(text(), "Allow gender mismatch")]/preceding-sibling::input

Personally I like the first approach more, since it still works even when the order of sibling-elements changes. With the second approach, you always need to check if the sibling is "preceding" or "following" (then you have to use following-sibling)

Upvotes: 2

gtlambert
gtlambert

Reputation: 11961

You need to add /preceding-sibling::input to your current XPath. So the final solution would be:

//div[@id="match_configuration_add_possible_tab_match_rules_fp_flags"]/span/label[contains(text(), "Allow gender mismatch")]/preceding-sibling::input

This selects the desired input element, so you can click it as required.

Upvotes: 1

Related Questions