You may consider using Helium - Selenium WebDriver wrapper which offers a jQuery-like selector as part of its API.
Assuming you are using WebDriver in Java, you can try the following code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import static com.heliumhq.API.*;
public class MyElementFinder {
public WebElement findMyElement() {
startChrome("YOUR-URL-HERE");
$ inboxMessageAttachment = $("#inbox_row_container_24_112 #inbox_message_attachment_24_112");
WebElement elem = inboxMessageAttachment.getWebElement();
do {
elem = elem.findElement(By.xpath("parent::node()"));
} while (!elem.getAttribute("id").equals("inbox_row_container_24_112"));
return elem;
}
}
Please note that your HTML code is not 100% valid - two of the <span>
tags do not have corresponding closing tags </span>
. If the HTML code was corrected and looked as following:
<a id="inbox_row_container_24_112" class="inbox_row_container row_even" href="javascript:void(0)">
<span id="inbox_message_24_112" class="inbox_message"></span>
<span id="inbox_message_attributes_24_112" class="inbox_message_attributes"></span>
<span id="inbox_message_attachment_24_112" class="inbox_message_attachment">*</span>
<span class="inbox_row_clear"></span>
</a>
Then the Helium script would have been much shorter and nicer:
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import static com.heliumhq.API.*;
public class MyElementFinder {
public WebElement findMyElement() {
startChrome("YOUR-URL-HERE");
$ inboxMessageAttachment = $("#inbox_row_container_24_112 > #inbox_message_attachment_24_112");
return inboxMessageAttachment.getWebElement().findElement(By.xpath("parent::node()"));
}
}
In the both above examples the findMyElement() method throws an exception of type NoSuchElementException if no such element exists - this can be handled to cover the case when there is no such element present.
Disclaimer: I'm one of Helium's developers