Guillaume
Guillaume

Reputation: 22822

Selenium: find element "next to" other element

I'm adding web tests to my project using Selenium. I already have a bunch of tests that check for a specific element using:

final WebElement dateElement = web.findElement(By.id(elementId));

And this works fine. Now I have another requirement. This is in my generated page:

<input type="text" id="dateElement" name="dateElement" value="bunch of monkeys" tabindex="101" placeholder="yyyy-mm-dd">
<span class="error">dateElement is an invalid date</span>

How can I get hold of the error message? I'd like something that allows me to request the span element with class "error" that is just after dateElement.

(This error message was ganerated by Spring MVC, so it's not easy to change it directly. Possible I guess, but I'd prefer not).

Any alternative idea is welcome.

Upvotes: 19

Views: 31418

Answers (2)

CBRRacer
CBRRacer

Reputation: 4659

elementSelector = "input + span[class='error']";

final WebElement dateElement = web.findElement(By.cssSelector(elementSelector));

Upvotes: 6

Guillaume
Guillaume

Reputation: 22822

OK, I already found a solution using Xpath and following-sibling, it wasn't too complicated.

final WebElement errorElement = web.findElement(By.xpath("//*[@id='" + elementId + "']/following-sibling::span[@class='error']"));

This gives me what I wanted, and throws a NoSuchElementException when it's not here, which is exactly what I want.

Upvotes: 28

Related Questions