Karthik
Karthik

Reputation: 11

How to get the text of a <div> tag which has sub elements along with direct text?

Can someone please help me in writing the XPath to get the text of a which contains some other elements as well along with the text. Below is the HTML code:

<div class="message success fadable">
  Successfully Deleted        
  <a class="messageCloseButton" href="#">Close</a>
</div>

Expected Value:

Successfully Deleted

Upvotes: 1

Views: 406

Answers (2)

Meenakshi Rana
Meenakshi Rana

Reputation: 545

Two ways to locate the element and fetch the div text and to verify the actual and expected Result.

1. Use Contains Method

     var element = driver.FindElement(By.XPath("//div[contains(text(),'Successfully Deleted')]"));
     string expectedResult = "Successfully Deleted";
     string actualResult = element.Text;
     Assert.AreEqual(expectedResult,actualResult);

2. Second

     var element = driver.FindElement(By.XPath("//div[@class = 'message success fadable'])]"));
     string actualText = element.Text;

Upvotes: 2

supputuri
supputuri

Reputation: 14135

Unfortunately you can not handle this situation in xpath. So you have to relay on the javascript to get the text nodes and return the value.

Here is the python solution.

def get_text_exclude_children(element):
    return driver.execute_script(
        """
        var parent = arguments[0];
        var child = parent.firstChild;
        var textValue = "";
        while(child) {
            if (child.nodeType === Node.TEXT_NODE)
                    textValue += child.textContent;
                    child = child.nextSibling;
        }
        return textValue;""",
        element).strip()

This is how to call this method in your case

ele = driver.find_element_by_xpath("//div[@class='message success fadable']")
print(get_text_exclude_children(ele))

enter image description here

Same Method in Java:

public String get_text_exclude_children(WebDriver driver, WebElement element) {
JavascriptExecutor js = (JavascriptExecutor) driver;  
return (String) js.executeScript("var parent = arguments[0];"
                                + "var child = parent.firstChild;"
                                + " var textValue = ''; while(child) { "
                                        + "if (child.nodeType === Node.TEXT_NODE)"
                                            + " textValue += child.textContent;"
                                            + " child = child.nextSibling; "
                                            + "} return textValue;",element);}

Upvotes: 0

Related Questions