Perkele Perkele - 3 months ago 23
Javascript Question

Selenium-WebDriver how to highlight element using javascript and firefox browser

I have a problem with creating valid function which will highlight certain defined elements on the webpage. Please note, that I am coding beginner, and the problem may be either simple environment setup issue, or lack of major knowledge of the javascript/selenium features.

I create my script in Eclipse Neon. To set up an environment I've installed node.js and geckodriver to be able to operate on firefox browser. The beginning of my script is:

var webdriver = require('selenium-webdriver'),
By = webdriver.By

var driver = new webdriver.Builder().forBrowser('firefox').build();


I open the webpage by using
driver.get();
and then I simply define the element location by using xPath ex.:

var element = driver.findElement(By.xpath("xPath goes here"));


And now the question begins, what should I do to make WebDriver to highlight this specified element with for ex. red border? While browsing the Stack and other similar pages, the only answers I found was something about using JavaScript Executor in Java syntax, or some webdriver functions using

element.style.backgroundColor = 'red'


but i get console error, that
style
or some other part of the syntax is not a function. At this point, I am out of solutions how to make this happen, and I slowly doubt, that I will be able to finish this task without the knowledge about html5/java. Maybe anyone has ever encountered such difficulty and will share the clue?

https://jsfiddle.net/osav574j/ <- I've prepared simplyfied version of my script which may give you a clue of how my full code looks like. The highlight part is probably wrong, it's just to show you, how I thought it may be done, but that's pure assumption.

Cheers!
Perkele

Answer

You should try using executeScript() as below :-

var element = driver.findElement(By.xpath("xPath goes here"));
driver.executeScrip‌t("arguments[0].style.backgroundColor = 'red'", element);
Comments