Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a parent element in webdriver.io

Tags:

webdriver-io

I've seen a couple of solutions in the original webdriver that use getAttribute('xpath') and append to that '/..' but webdriver.io doesn't have an xpath attribute so I haven't been able to use that. Any ideas on how to grab the parent element?

The case I am trying to test is inside of a bootstrap layout and the element that is actually getting the class I am trying to check is one above. It looks like this:

<div class="form-group">
  <input class="form-control" type="text" name="username">
  <other stuff>
</div>

I am selecting by driver.element("input[name='username'"] but the error class actually hits the div

<div class="form-group error">
  <input class="form-control" type="text" name="username">
  <other stuff>
</div>

So I need to check if the div itself has an error class, not the input I can find (there are no uniques on the div)

Any help would be greatly appreciated.

like image 307
Ben Hernandez Avatar asked Aug 17 '16 17:08

Ben Hernandez


2 Answers

Just searched the same and found this by inspecting Webdriver.IO source code - you can use el.$('..') to get the parent element, like this:

$('input[name="username"]').$('..') // returns the parent element

Voila! It's a part of their XPath selectors support.

like image 112
Artem Vasiliev Avatar answered Dec 29 '22 07:12

Artem Vasiliev


I ended up solving this by using execute to get the xpath from jQuery, here is the code I used (albeit for a different test I was writing - if every label that has a * is a required field). Hopefully this is helpful to somebody in the future:

var requiredXPaths = browser.execute(function () {
var returner = [];
var $elements = $('.modal.fade.in').find("label:contains('*')");
  _.each($elements, el => {
    var xpath = '';
    var element = el.parentElement;
    for (; element && element.nodeType == 1; element = element.parentNode) {
      var id = $(element.parentNode).children(element.tagName).index(element) + 1;
      id > 1 ? (id = '[' + id + ']') : (id = '');
      xpath = '/' + element.tagName.toLowerCase() + id + xpath;
    }

    returner.push(xpath);
  });
  return returner;
});

I got the xPath function from another stackoverflow page (How to calculate the XPath position of an element using Javascript?)

like image 21
Ben Hernandez Avatar answered Dec 29 '22 08:12

Ben Hernandez