44

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
});
Dr1Ku
  • 2,690
  • 3
  • 43
  • 52
rsboarder
  • 3,822
  • 3
  • 16
  • 21

4 Answers4

45

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

kamituel
  • 30,600
  • 3
  • 71
  • 91
23

Decided to use xpath.

var row = results[randomNum].findElement(by.xpath('ancestor::tr'));
rsboarder
  • 3,822
  • 3
  • 16
  • 21
  • 26
    `by.xpath('..')` would also give you the parent element. – borisdiakur May 14 '14 at 14:02
  • 1
    Does this work anymore? I can't see any reference to xpath in the docs now. – mariachimike Aug 23 '14 at 05:21
  • 3
    @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. – Sirk Oct 15 '14 at 08:43
  • Failed: element(...).findElement is not a function – Justin Mar 20 '18 at 20:11
10

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.

hkievet
  • 169
  • 1
  • 12
  • 2
    The other answers are outdated (though still functional), this one works great and is more concise. Thanks! – Gunderson May 17 '17 at 15:45
  • 1
    Failed: element(...).getDriver is not a function – Justin Mar 20 '18 at 20:09
  • @Justin thanks for pointing that out! It looks like Protractor was updated to require using `getWebElement()` to call getDriver(). I updated my answer! – hkievet Mar 21 '18 at 20:51
2

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

quirimmo
  • 9,161
  • 1
  • 24
  • 43