Reputation: 11
Is it possible find element inside another element? If we have html like this one
<div>
<span>Some text 1 </span>
<p>Other text 1</p>
</div>
<div>
<span>Some text 2 </span>
<p>Other text 2</p>
</div>
<div>
<span>Some text 2 </span>
<p>Other text 2</p>
</div>
is it possible to do something like this
IList<IWebElement> elements=driver.FindElements(By.TagName("div"));
for (int i = 0; i < elements.Count; i++)
{
string text= elements[i].FindElement(By.TagName("span")).Text;
}
I have tried multiple times and in second iteration it is always finding me the the text from first element.
Upvotes: 0
Views: 3721
Reputation: 25744
Use a CSS selector and let it do the work for you...
foreach (IWebElement element in Driver.FindElements(By.CssSelector("div > span")))
{
Console.WriteLine(element.Text);
}
This will find all SPANs that are children (>) of a DIV.
Upvotes: 1
Reputation: 19184
do you want to get p
and span
inside div
?
using Xpath()
or CssSelector()
IList<IWebElement> div_childs = driver.FindElements(By.Xpath("//div/*"));
// or
//IList<IWebElement> div_childs = driver.FindElements(By.CssSelector("div *"));
foreach (var child in div_childs)
{
string text = child.Text;
string tag_name = child.TagName;
}
Upvotes: 1