Perkele Perkele - 1 year ago 174
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
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 = 'red'

but i get console error, that
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? <- 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.


Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download