Eve
Eve

Reputation: 785

selenium find child's child elements

I have following html like:

<form name="form1">
  <input name="a" ...>
  <input name="b" ...>
  ...
  <div><span><select name="c">...</select></span></div>
</form>

I would like to find out all elements within the form element. First I use findElement() to get the form element form1, then use form1.findElements(By.xpath(".//*[@name]")) to get all its children having attribute name. However, for the select element, since it's grand-grand child of form1, how can I get it as well?

Is there a way to find all elements containing attribute name (not only child elements, but also child's child's child...) within form1?

Thanks!

Upvotes: 8

Views: 41350

Answers (3)

AlignedDev
AlignedDev

Reputation: 8232

You should be able to use the descendant:: as described in this post.

http://hedleyproctor.com/2011/05/tutorial-writing-xpath-selectors-for-selenium-tests/

Here are a few examples from the article:

//div[h3/text()='Credit Card']/descendant::*
//div[h3/text()='Credit Card']/descendant::input[@id='cardNumber']
//div[*/text()='Credit Card']/descendant::input[@id='cardNumber']



  webDriver.findElement(
     By.xpath("//div[*/text()='Credit Card']/descendant::input[@id='cardNumber']")
  ).sendKeys("1234123412341234");

Upvotes: -1

Alan Donizete
Alan Donizete

Reputation: 448

if you want to get an WebElement by xpath, and so get child of it... you may use webElement.findElement(By.xpath("./*")) ... this "." before the "/" makes the magic, you'll need it to get only the children of the webElement...

Upvotes: 17

Robbie Wareham
Robbie Wareham

Reputation: 3428

Do you have to find the form element? If not, then you can do it in one select statement using css or xpath.

The css would be 'form[name="form1"] [name]'

Note the space between the closing and opening brackets.

You would use this selector with FindElement on the driver object rather than finding the form first.

Upvotes: 0

Related Questions