8

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!

Eve
  • 785
  • 3
  • 7
  • 15
  • What you already have should work since it's not just finding children, but any descendants nested at any level. – BoltClock Nov 26 '13 at 12:23
  • But when I run it, I only get the children elements, not all descendants.@BoltClock'saUnicorn – Eve Nov 26 '13 at 12:32
  • Thanks@BoltClock'saUnicorn Yes, you're right. I made a mistake because in google page, I think they use `` to express the select element while the source code displayed as ` – Eve Nov 26 '13 at 12:41

3 Answers3

17

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...

Alan Donizete
  • 438
  • 5
  • 12
0

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.

Robbie Wareham
  • 3,380
  • 1
  • 20
  • 38
-1

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");
AlignedDev
  • 8,102
  • 9
  • 56
  • 91