I have this piece of JavaScript code that I run in chrome console to add all the values of a column from a web table:
var iRow = document.getElementById("DataTable").rows.length
var sum = 0
var column = 5
for (i=1; i<iRow; i++){
var retail = document.getElementById("DataTable").rows[i].cells.item(5).innerText
var splitRetailPrice = retail.split(" ")
for(j=0; j<splitRetailPrice.length; j++){
var trimValue = splitRetailPrice[1]
var intPrice = Number(trimValue)
sum += intPrice
break
}
}
console.log(sum)
If I do it traditionally in selenium webdriver with a locator, ex: driver.findElement...., it takes me more than 5 minutes to complete the task cause the web table reproduces more than 7 thousand rows. I'm assuming this will make it much faster.
Question: How can I run this piece of code in selenium using java?
Question: Would it be a good idea?
I know it has something to do with JavascriptExecutor but I don't know how to implement it.
I see everyone is demonstrating one line of code everywhere with a return. It will be helpful if someone can show me how to incorporate multiple lines of codes given above and return the value. Preferably in a method which will return the value.
SECOND ATTEMPT:
I've tried this now, following what was suggested as duplicate :
JavascriptExecutor js = (JavascriptExecutor)driver;
String val = (String) js.executeScript(
"return"+
"var iRow = document.getElementById('DataTable').rows.length"+
"var sum = 0"+
"for (i=1; i<iRow; i++){"+
"var retail = document.getElementById('DataTable').rows[i].cells.item(5).innerText"+
"var splitRetailPrice = retail.split("+" "+")"+ //passing a space as a delimiter.
"for(j=0; j<splitRetailPrice.length; j++){"+
"var trimValue = splitRetailPrice[1]"+
"var intPrice = Number(trimValue)"+
"sum += intPrice"+
"break"+
"}"+
"}");
System.out.println(val);
I'm getting: org.openqa.selenium.JavascriptException: SyntaxError: unexpected token: identifier
Can someone tell me what's wrong here?