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.
finalStringscript= FileUtils.readFileToString(newFile("script.js"), "UTF-8");
JavascriptExecutorjs= (JavascriptExecutor)driver;
...
WebElementelement= driver.findElement(By.anything("myElement"));
Stringtext= (String)js.executeScript(script, element);
Post a Comment for "Counting Inner Text Letters Of Html Element"