Wednesday, April 14, 2021

How to get text from parent element and exclude text from children (C# Selenium)

Example: Suppose you have the following DOM

<h2 class="title">Charger

<div class="default"> 

<span>method</span> 

<span class="sr-only">Default</span>

</div> 

</h2>


<h2 class="title">Mobile

<div class="default"> 

<span>method</span> 

<span class="sr-only">Default</span>

</div> 

</h2>


<h2 class="title">Cable

<div class="default"> 

<span>method</span> 

<span class="sr-only">Default</span>

</div> 

</h2>

Solution: You can use the below code to fetch the parent element texts (i.e. Charger, Mobile and Cable) IList list = Application.driver.FindElements(By.XPath("//h2")); string[] texts = new string[list.Count]; foreach (IWebElement element in list) { texts[i] = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].firstChild.textContent;", element); i++; } return texts;