1

I want to get the value from an element based on the element preceding it. For example, getting the value "YYYY-MM-DD" based on the element "date"

Here is the html snippet:

enter image description here

4 Answers 4

2

If the value you need to extract is in the input element, you can use the following xpath;

//div[contains(text(), 'date:')]/ancestor::div[contains(@class, 'form row')]/following-sibling::input[@id=formData-rest_of_the_id_value]

Its better to use id attribute to locate web elements, because it is unique to the web element.

Check this tutorial for more on xpath

1

If the element is unique then use :

//div[contains(text(), 'date:')]

If you believe that the parent element is unique and not the target element then,

You could just do:

//div[contains(@class, 'form row')]/div[contains(text(), 'date:')]

You don't have to check sibling.

Here // means anywhere in the HTML DOM, / means direct child. So the given locator finds direct child of div[contains(@class, 'form row')].

1

I used the following xpath

//div[contains(text(),'date')]/ancestor::div[contains(@class, 'form-row')]/following-sibling::div/div/div[@class='_textContainer_psmgei']

but can there be a better way?

1
  • You can try the following: //div[contains(text(),'date')]/ancestor::div[contains(@class, 'form-row')]/following-sibling::div//input[@type='text']::preceding-sibling::div
    – the_coder
    Commented May 22, 2020 at 12:23
0

I think input[@id=formData-rest_of_the_id_value] "rest_of_the_id_value" is auto-generated value and it will change all the time.

I prefer this way

//div[contains(text(),'date')]/ancestor::div[contains(@class,'form-row')]/following-sibling::div//div[contains(@style,'position']

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.