How to get the parent of an element

28,727

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

Share:
28,727

Related videos on Youtube

rsboarder
Author by

rsboarder

Updated on July 09, 2022

Comments

  • rsboarder
    rsboarder almost 2 years

    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
    });
    
  • borisdiakur
    borisdiakur almost 10 years
    by.xpath('..') would also give you the parent element.
  • mariachimike
    mariachimike over 9 years
    Does this work anymore? I can't see any reference to xpath in the docs now.
  • Sirk
    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
    Gunderson almost 7 years
    The other answers are outdated (though still functional), this one works great and is more concise. Thanks!
  • Justin
    Justin about 6 years
    Failed: element(...).getDriver is not a function
  • Justin
    Justin about 6 years
    Failed: element(...).findElement is not a function
  • hkievet
    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!