rsboarder
rsboarder

Reputation: 4782

How to get the parent of an element

For example, I am randomly picking a button element from within the rows of a table.
After the button is found, I want to retrieve the table'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
});

Upvotes: 44

Views: 29669

Answers (4)

hkievet
hkievet

Reputation: 169

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.

Upvotes: 10

quirimmo
quirimmo

Reputation: 9988

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();

Upvotes: 2

rsboarder
rsboarder

Reputation: 4782

Decided to use xpath.

var row = results[randomNum].findElement(by.xpath('ancestor::tr'));

Upvotes: 23

kamituel
kamituel

Reputation: 35960

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()).

Upvotes: 44

Related Questions