htmlxpathsiblings

Xpath selecting Input Radio based on following text


I have this HTML code:

<input type="radio" class="inputs-highlight" name="country"><h2>Russia</h2>
<input type="radio" class="inputs-highlight" name="country"><h2>USA</h2>
<input type="radio" class="inputs-highlight" name="country"><h2>Other</h2>

I'm trying to select the input radio where the text is equal to "Other".

I tried with:

 .//input[./@type = 'radio']/following::*[text() = "Other"]

But this is returning the H2 element not the Input Radio element.

And with this:

 //input[@type='radio' and following-sibling::text() = 'Other']

there is no result.

Thanks for the help in advance.


Solution

  • You have to select the first occurrence:

    //input[@type="radio"][following-sibling::*[1]/text()='Other']
    

    since it is true that there exists an element containing Other after the selected input. The expression above selects only the inputs where the next sibling contains Other.