I have the following HTML:
<p class="p-class-name">
Normal Text 1
<a href="" target="_blank" rel="noopener noreferrer">Link Text</a>
Normal Text 2
<a href="" target="_blank" rel="noopener noreferrer">Link Text</a>
</p>
If I select the <p>
tag using the class selector p-class-name
and click on it, the click somehow happens on one of those <a>
tags inside the <p>
. I want to be able to click on the Normal Text 1
. How can I get the text node from the <p>
tag and click on it?
I have tried the following:
public static IEnumerable<IWebElement> GetChildren(this IWebElement element)
{
return element.FindElements(By.XPath($"child::*"));
}
But, this will only return the two a
tags (excluding the text nodes).
I have noticed that element.childNodes
in JavaScript returns the text nodes as well. So tried this:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var el = (IWebElement)js.ExecuteScript("return document.getElementsByClassName('p-class-name')[1].childNodes[0]");
This results in the error:
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'OpenQA.Selenium.IWebElement'.'
CodePudding user response:
You have to induce IJavaScriptExecutor
IWebElement e = Driver.FindElement(By.XPath($"//p[contains(@class,'p-class-name')]"));
var el = (IWebElement)((IJavaScriptExecutor)Driver).ExecuteScript("return arguments[0].childNodes[1];", e);
el.Click();
or
IWebElement e = Driver.FindElement(By.XPath($"//p[contains(@class,'p-class-name')]"));
((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].childNodes[1].click();", e);