How to get the parent of an element
Solution 1
Decided to use xpath.
var row = results[randomNum].findElement(by.xpath('ancestor::tr'));
Solution 2
As of the most recent Protractor (1.6.1 as of this writing), the syntax changed a bit:
var row = results[randomNum].element(by.xpath('..'));
(use element()
instead of findElement()
).
Solution 3
You can now use
var element = element(by.css('.foo')).getWebElement()
var parentElement = element.getDriver() // gets the parent element
to get the parent element. See http://www.protractortest.org/#/api?view=webdriver.WebElement.prototype.getDriver for more info.
Solution 4
Actually, at the moment there is an easier way to select the parent of an element avoiding to use xpath
.
From an ElementFinder
you can simply access the parent element through parentElementArrayFinder
and for example then trigger directly the click
method:
myElement.parentElementArrayFinder.click();
Related videos on Youtube
rsboarder
Updated on July 09, 2022Comments
-
rsboarder almost 2 years
For example, I am randomly picking a
button
element from within the rows of atable
.
After thebutton
is found, I want to retrieve thetable
's row which contains a selected button.Heres is my code snippet:
browser.findElements(by.css('[ng-click*=submit]')).then(function (results) { var randomNum = Math.floor(Math.random() * results.length); var row = results[randomNum]; // ^ Here I want to get the parent of my random button });
-
borisdiakur almost 10 years
by.xpath('..')
would also give you the parent element. -
mariachimike over 9 yearsDoes this work anymore? I can't see any reference to xpath in the docs now.
-
Sirk over 9 years@mariachimike you have probably figure this out by now but for future searchers, i am on protractor 1.3.0 and 'element(by.xpath('..'))' still works. The current latest version is 1.3.1 and the changelog only includes one fix so it will work in that as well, i cant imagine it would be taken out in the near future if ever.
-
Gunderson almost 7 yearsThe other answers are outdated (though still functional), this one works great and is more concise. Thanks!
-
Justin about 6 yearsFailed: element(...).getDriver is not a function
-
Justin about 6 yearsFailed: element(...).findElement is not a function
-
hkievet about 6 years@Justin thanks for pointing that out! It looks like Protractor was updated to require using
getWebElement()
to call getDriver(). I updated my answer!