i have the following HTML
<div id="element1">welcome</div>
<div>username</div>
Now the problem is, i have to select the next div element next to "element1". I know,i can build xpath from their parent. But it i need to pick one which is very next to an element. How it is possible ?
Use the following-sibling
axis.
This selects all sibling <div>
elements after the element1
node:
id('element1')/following-sibling::div
This selects the first sibling <div>
element after the element1
node:
id('element1')/following-sibling::div[1]
This selects the first sibling node after the element1
node iff it's a <div>
element:
id('element1')/following-sibling::*[1][local-name(.)='div']
All those three examples will select your element (and maybe some more if there are any more matching), so pick one which suits your intent the most.
Note that you can do all this with a simple CSS selector, too. It's equivalent to the last XPath. And it will be faster.
#element1 + div
You can use the following-sibling
:
driver.findElement(By.id("element1")).findElement(By.xpath("./following-sibling::div"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With