0

Here is my sample source HTML:

<!-- Many other elements above this -->

<div class="emf-div-field">
    <span style="width:175px">
        <input class="validate[required]" style="width:100%" value="" id="element_2" name="element_2" type="text">
        <label for="element_2" class="emf-bottom-label emf-text-center">First</label>
    </span>

    <span style="width:125px">              
        <input class="validate[optional]" style="width:100%" value="" id="element_6" name="element_6" type="text">
        <label for="element_6" class="emf-bottom-label emf-text-center">Middle</label>
    </span>

    <span style="width:175px">
        <input class="validate[required]" style="width:100%" value="" id="element_3" name="element_3" type="text">
        <label for="element_3" class="emf-bottom-label emf-text-center">Last</label>
    </span>

</div>

<!-- Many other elements below this -->

I need the XPath to select the <input> element just prior to the <label> element whose innerText is "First". The <input> element is always a sibling of the <label> element.

It needs to be a relative selection, based on the <label> innerText because in general these statements could be at many different levels.

I have tried this (and many other variations), but none have worked:

//input[preceding-sibling::label[text() = "First"]]

Thanks.

3
  • Sadly, most CSS innertext selectors have been removed from the spec, most of it has to be done via JQuery or JS now ! Commented Oct 16, 2019 at 23:06
  • Do you have any control over the <label> tag? Can you make it: <label for="element_2" class="emf-bottom-label emf-text-center" text="First">First</label> and use the css selector div span input+label[text="First"] { color: red; } ? Commented Oct 17, 2019 at 0:16
  • Why did someone give my question a negative vote??? If you did it, please have the guts and integrity to post your reason. Commented Oct 18, 2019 at 1:13

1 Answer 1

1

Don't make it too complicated. Just use

//span[label='First']/input

But if you really need a path relative to the label element, use

//label[.='First']/preceding-sibling::input[1]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @zx485! That is perfect. 👍 I have another more complicated XPath question, but I'm make a separate question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.