Parent of a WebElement

663 views
Skip to first unread message

Tomas

unread,
Aug 21, 2009, 1:19:24 AM8/21/09
to webdriver
Hello all,

I'm using webdriver to test the structure of a rendered page.

I obtain a known WebElement using its id, and would like to get its
parent element to assert some condition. I'm looking for something
like WebElement.getParent(), but there isn't such a method.

Is there a way to achieve this? If not, would it be difficult to
implement?

Thanks in advance,
Tomas

Simon Stewart

unread,
Aug 23, 2009, 8:11:11 AM8/23/09
to webdriver
Hi,

I've avoided making it too easy to generalised walks of the DOM with
webdriver because IME these tend to be abused, which why there's no
"getParent" method. Having said that, and in the spirit of making "the
hard things possible", there are two ways to get the parent node,
firstly be executing the following JS:

var e = arguments[0];
if (e['parentElement']) {
// Handles IE
return e.parentElement
}
// Walk the DOM until we find the parent
var p = e.parentNode;
while (p.type != 1) {
p = p.parentNode;
}

Using something like:

WebElement parent = (WebElement)
((JavascriptExecutor) driver).executeScript(
script, element);

Or, more simply:

WebElement parent = element.findElement(By.xpath(".."));

Cheers,

Simon

2009/8/21 Tomas <tpoll...@gmail.com>:

Tomás Pollak

unread,
Aug 23, 2009, 7:59:22 PM8/23/09
to webd...@googlegroups.com
Hi Simon,

thanks for the quick reply. It worked.

Cheers,
Tomás

On Sun, Aug 23, 2009 at 9:11 AM, Simon Stewart <simon.m...@gmail.com> wrote:

Hi,

I've avoided making it too easy to generalised walks of the DOM with
webdriver because IME these tend to be abused, which why there's no
"getParent" method. Having said that, and in the spirit of making "the
hard things possible", there are two ways to get the parent node,
firstly be executing the following JS:

var e = arguments[0];
if (e['parentElement']) {
 // Handles IE
 return e.parentElement
}
// Walk the DOM until we find the parent
var p = e.parentNode;
while (p.type != 1) {
 p = p.parentNode;
}

Using something like:

WebElement parent = (WebElement)
 ((JavascriptExecutor) driver).executeScript(
     script, element);

Or, more simply:

WebElement parent = element.findElement(By.xpath(".."));

Cheers,

Simon

Reply all
Reply to author
Forward
0 new messages