12

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.

Ben Hernandez
  • 787
  • 10
  • 21

4 Answers4

29

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.

Artem Vasiliev
  • 1,585
  • 1
  • 17
  • 19
1

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?)

Community
  • 1
  • 1
Ben Hernandez
  • 787
  • 10
  • 21
0

WebdriverIO actually lets you use XPath in your selectors, so any valid Xpath selector should work to find the element you want.

Alternatively, you could just use isExisting to check if the element exists on the page using the error class parent:

driver.isExisting('.error input[name="username"]');

If the element doesn't exist, then your error class didn't get added.

Kevin Lamping
  • 2,079
  • 15
  • 19
0

I've been talking about this in gitter, when the parent can be selected input[name="username"]

The parent of this element can be selected as //div[input[name="username"]]

Mathieu Brouwers
  • 524
  • 6
  • 18