0

I have a protractor webElementFinder testElement. I want to match only its div children (NOT grandchildren or any other further descendants) and thus testElement.find('div') will not work as it will find all descendant divs.

If protractor worked like jQuery (which would make sense since Angular is smart enough to use jQuery if its present and protractor is built with Angular in mind), I would just do testElement.find(' > div') which would work despite the find argument not being a valid CSS selector by itself; however because protractor just uses built in Element functions, that CSS selector is not valid by itself, and protractor throws an error.

I could go this route Angular JS, Protractor locator, get direct children of element since xpath natively lets you look at children, but I'd much rather use CSS than xpath.

Community
  • 1
  • 1
Tahsis Claus
  • 1,879
  • 1
  • 15
  • 27

3 Answers3

3

There is no direct and easy way to have a direct parent-child locator from the current element. A common way to solve it is to use the ./ XPath expression, but there is also this "hack" that uses locator():

testElement.$(testElement.locator().value + ' > div');
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

Just use:

$('testElement > div')
Bob Bai
  • 283
  • 4
  • 20
0

The solution depends on a few things:

  1. if testElement is an ElementFinder (const testelement = element(by.css('.some-selector'))), then you can do testelement.all(by.css('div')). Be aware of the all, because you are talking about chrildren, you will find all children with all. It will return an ElementArrayFinder, see the docs
  2. if testElement is a selector (const foo = '.testElement'), then you can do $$('.testElement > div'). This will return all the It will return an ElementArrayFinder, see the docs

I hope you can add the selector of testElement to the css selector with the >, the advantage you will get from this is that you will get all elements that are a direct children of the testElement-selector

wswebcreation
  • 2,365
  • 2
  • 10
  • 18