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

I have a problem creating a valid function that highlights certain specific elements on a web page. Please note that I am starting to program, and the problem may be either a simple problem setting up the environment, or a lack of a lot of knowledge about javascript / selenium functions.

I create my script in Eclipse Neon. To set up the environment, I installed node.js and geckodriver to be able to work in the Firefox browser. The beginning of my script:

var webdriver = require('selenium-webdriver'), By = webdriver.By var driver = new webdriver.Builder().forBrowser('firefox').build(); 

I open a webpage with driver.get(); and then just locate the element using xPath ex .:

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

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

 element.style.backgroundColor = 'red' 

but I get a console error that style or some other part of the syntax is not a function. At the moment, I have no decisions on how to do this, and I slowly doubt that I can finish this task without knowledge of html5 / java. Has anyone ever encountered such difficulties and is sharing a key?

https://jsfiddle.net/osav574j/ <- I just prepared a version of my script that can give you an idea of ​​how my complete code looks like. The exceptional part is probably incorrect, it just shows you how I thought it could be done, but this is a pure assumption.

Hooray! Perkele

+5
source share
2 answers

You should try using executeScript() as shown below: -

 var element = driver.findElement(By.xpath("xPath goes here")); driver.executeScripβ€Œt("arguments[0].style.backgroundColor = 'red'", element); 
+2
source

This is Javascript code to highlight an element. Selenium has no native method to allocate, so the only way out is to use code similar to this:

 JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("arguments[0].setAttribute('style,'border: solid 2px red'')", username); 

Here, the username is the name of the web element.

0
source

All Articles