1

I want to get list of similar element into arraylist using javascriptexecutor. However able to store only single element using javascriptexecutor. Here is my code:

JavascriptExecutor js = (JavascriptExecutor)driver;
Objectload=js.executeScript("document.evaluate(\"//article/footer/div[1]/h3/text()[2]\",document,null, XPathResult.STRING_TYPE, null ); return stringValue;");

using this i found only single locator however other element in similar kind of xpath "//article/footer/div[1]/h3/text()[2]\" also exist. Can you plz help me to resolve this..

2

List of similar elements can be found by JavascriptExecutor using selenium webdriver in following way:

JavascriptExecutor js = (JavascriptExecutor)driver;

    List<WebElement> eles = (List<WebElement>) js.executeScript("var results = new Array();"
            + "var element = document.evaluate(\"//h3[@class='location']\", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);"
            + "for ( var i = 0 ; i < element.snapshotLength ; i++ )"
            + "{"
            +    "results.push(element.snapshotItem(i));"
            + "}"
            + "return results;","");

In the above code it is necessary that XpathResult is of SNAPSHOT type.

Through the above list we would get all the elements with h3 tag having class='location'. From then on we can convert those elements into Strings.

List<String> strings = new ArrayList<>();
for(WebElement e : eles)
{
  strings.add(e.getText());
}

Following links have been helpful:

  1. findElementsByXpath in Javascript: https://gist.github.com/tit/4695818
  2. https://stackoverflow.com/questions/36303869/how-to-use-document-evaluate-to-get-the-list-of-elements-pointed-by-xpath

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.