Skip to content Skip to sidebar Skip to footer

Counting Inner Text Letters Of HTML Element

Is there a way to count the letters of inner text of an HTML element, without counting the letters of inner element's texts? I tried out the '.getText()' method of 'WebElements' us

Solution 1:

Based on this answer for a similar question, I cooked you a solution:

The piece of JavaScript takes an element, iterates over all its child nodes and if they're text nodes, it reads them and returns them concatenated:

var element = arguments[0];
var text = '';
for (var i = 0; i < element.childNodes.length; i++)
    if (element.childNodes[i].nodeType === Node.TEXT_NODE) {
        text += element.childNodes[i].textContent;
    }
return text;

I saved this script into a script.js file and loaded it into a single String via FileUtils.readFileToString(). You can use Guava's Files.toString(), too. Or just embed it into your Java code.

final String script = FileUtils.readFileToString(new File("script.js"), "UTF-8");
JavascriptExecutor js = (JavascriptExecutor)driver;

...

WebElement element = driver.findElement(By.anything("myElement"));
String text = (String)js.executeScript(script, element);

Post a Comment for "Counting Inner Text Letters Of HTML Element"