R Sawant
R Sawant

Reputation: 241

Get only inner text from webelemnt

I want to get only innerText from a webelement. I want to get only "Name" from the anchor tag.I have access to webdriver element associated with tag in below example(anchorElement). I tried anchorElement.getText() and anchorElement.getAttribute("innerText"). Both return me "Name, sort Z to A". What should I do here ?

<a id="am-accessible-userName" href="javascript:void(0);" class="selected">
Name 
<span class="util accessible-text">, sort Z to A</span> 
<span class="jpui iconwrap sortIcon" id="undefined" tabindex="-1"> 
<span class="util accessible-text" id="accessible-"></span> 
<i class="jpui angleup util print-hide icon" id="icon-undefined" aria-hidden="true"></i>
</span>
</a>

Upvotes: 1

Views: 1032

Answers (3)

Phani
Phani

Reputation: 1

The text alone could be obtained by using proper javascript code to iterate through child nodes of a given weblement and then returning text if the current node is a text node. Note: A trimmed value of node text will be returned.

public String getInnerText(WebDriver e, String xpathStr){
WebElement ele = e.findElement(By.xpath(xpathStr));
        return ((String) ((JavascriptExecutor) e).executeScript("var children = arguments[0].childNodes;\n" +
                "for(child in children){\n" +
                "   if(children[child].nodeName === \"#text\"){" +
                "  return children[child].nodeValue };\n" +
                "}" , ele )).trim(); 
}

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193058

As per the HTML the desired element is a Text Node and also the First Child Node of the <a> tag. So to extract the text Name you can use the following code block :

  • Java Binding Art :

    WebElement myElement = driver.findElement(By.xpath("//a[@class='selected' and @id='am-accessible-userName']"));
    String myText = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", myElement);
    System.out.println(myText);
    

Upvotes: 0

df778899
df778899

Reputation: 10931

A bit of Javascript can pick out just the child text node:

RemoteWebDriver driver = ...
WebElement anchorElement = driver.findElement(By.id("am-accessible-userName"));
String rawText = (String) driver.executeScript(
    "return arguments[0].childNodes[0].nodeValue;", 
    anchorElement);

So anchorElement is passed into the Javascript as arguments[0] there.

Clearly childNodes[0] is assuming where the text node is. If that's not safe, you could iterate the childNodes too, perhaps checking for childNode.nodeName === "#text"

Upvotes: 3

Related Questions