How to exclude text content of child elements of the parent element in Selenium WebDriver is explained in this post.

We can achieve this with help of jQuery.

To understand this topic one should know, how to execute jQuery with Selenum WebDriver, refer previous post run jQuery

To explain this, took the google.com website as an example. In the bottom of this page it has supported languages, those are maintained in a parent div tag with child tags. I want to get the text of the parent tag only, that is “Google.co.in offered in:”

If we write the locator for the parent div tag and then get the text with WebDriver Api getText(),

  • WebElement supLanguages=driver.findElement(By.cssSelector("div#_eEe"));
    supLanguages.getText();
    

It will give you all the supported languages along with text in parent, that is “Google.co.in offered in: हिन्दी  বাংলা  తెలుగు  मराठी  தமிழ்  ગુજરાતી  ಕನ್ನಡ  മലയാളം  ਪੰਜਾਬੀ “

How to Exclude text content OF child element

Following are the two ways

1.

  1. $("div#_eEe").clone().children().remove().end().text();
    
    • Here clone() method will clone the entire element
    • children() method will get the all children’s of the parent element
    • remove() method will remove the fetched children’s
    • end() method is used for filtering option that will return the cloned parent again.
    • text() method will return the text in the parent.
  2. $("div#_eEe").contents().filter(function(){ return this.nodeType == 3; }).text();
    
    • Here contents() will get the childrens of the matched elements, including text and comment nodes.
    • Applied filter to get the parent node text content.
    • nodeType property returns the node type in number format
      • return #1 if the node is an element node
      •  return 3 if the node is a text node.

Below is the complete code.

package com.exploreselenium;

import java.io.File;
import java.lang.Class;

import com.google.common.io.Resources;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.URL;

public class RunJquery {

    WebDriver driver;
    JavascriptExecutor js;

    @FindBy(id="lst-ib") WebElement googleTxtBox;
    @FindBy(css="div#_eEe") WebElement supportedLanguages;

    @BeforeClass
    public void browserInstantiate() {
        //System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\chromedriver.exe");
        System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\geckodriver.exe");
        driver=new FirefoxDriver();
        //driver = new ChromeDriver();
        js=(JavascriptExecutor)driver;
        PageFactory.initElements(driver, this);
    }

    @Test
    public void getTextFromParent() throws Exception{
        driver.get("http://google.com");
        verifyElementVisible(googleTxtBox);
        WebElement supportedLanguages=driver.findElement(By.cssSelector("div#_eEe"));
        System.out.println(supportedLanguages.getText());
        enablejQuery();
        System.out.println(js.executeScript("return $(\"div#_eEe\").clone().children().remove().end().text();"));
    }

    public void enablejQuery() throws Exception{
        String readyState = js.executeScript("return document.readyState").toString();
        System.out.println("Ready State: " + readyState);
        System.out.println("Is Jquery loaded......" + isjQueryLoaded());
        if(!isjQueryDefined()) {
            URL jqueryUrl = Resources.getResource("jquery-3.1.1.min.js");
            System.out.println(jqueryUrl.getPath());
            String jqueryText = Resources.toString(jqueryUrl, Charsets.UTF_8);
            js.executeScript(jqueryText);
        }
        System.out.println("Is Jquery loaded......" + isjQueryLoaded());
    }

    public Boolean isjQueryDefined() throws Exception {
        return (Boolean) js.executeScript("return !!window.jQuery;");
    }

    public void verifyElementVisible(WebElement element){
        new WebDriverWait(driver,30).until(ExpectedConditions.visibilityOf(element));

}

Here is the output. It has logged text that is fetched with WebDriver getText() API and jQuery as well.

  • First line fetched with getText()
  • Last line fetched with jQuery
  • Google.co.in offered in: हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ
    Ready State: complete
    Is Jquery loaded......false
    /G:/ExploreSelenium/target/test-classes/jquery-3.1.1.min.js
    Is Jquery loaded......true
    Google.co.in offered in:
    
Summary:

Here we learned how to fetch text content of a parent element by exclude it’s children element content text with jQuery in Selenium WebDriver.

 

Fetch authorization headers through headless browser for API Automation
Run jQuery in Selenium WebDriver
0