Reputation: 211
I am using Selenium via c#. I use this XPath to get all the children elements
element.FindElements(By.XPath("./child::*"));
Although if there is no child, it throws an error after a timeout. I am looking for a simple way to determine if it has a child or not to avoid the exception.
Upvotes: 3
Views: 15725
Reputation: 344
To do in Javascript:
var childElements = await element.findElements(By.xpath('.//*'));
for (i = 0; i <= childElements.length; i++) {
var elementId = await childElements[i].getAttribute("id");
await console.log(elementId);
}
Upvotes: 1
Reputation: 1
The simplest way is:
boolean hasChildren(WebElement node) {
return node.findElements(By.xpath("./descendant-or-self::*")).size() > 1;
}
Upvotes: 0
Reputation: 445
bool HasChild(IWebElement element)
{
//Save implicit timeout to reset it later
var temp = driver.Manage().Timeouts().ImplicitWait;
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
bool exists = element.FindElements(By.XPath(".//*")).Count > 0;
driver.Manage().Timeouts().ImplicitWait = temp;
return exists;
}
Upvotes: 0
Reputation: 193058
As per your question to get all the Child Nodes of a Parent Node you can use FindElements()
method with following-sibling::* attribute within xpath as follows :
Sample Code Block :
List<IWebElement> textfields = new List<IWebElement>();
textfields = driver.FindElements(By.XPath("//desired_parent_element//following-sibling::*"));
Note : When FindElements()
is used inconjunction with implicitly or explicitly waits, FindElements()
method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
XPath Details :
Upvotes: 3
Reputation: 98
FindElements returns a list, so you can check the size of the list, if it is zero, it means there are no child elements
Java
List<WebElement> childs = rootWebElement.findElements(By.xpath(".//*"));
int numofChildren = childs.size();
C#
IReadOnlyList<IWebElement> childs = rootWebElement.FindElements(By.XPath(".//*"));
Int32 numofChildren = childs.Count;
Upvotes: 2