Sunday, March 27, 2016

Highlight an Element using Selenium Web Driver

Sometimes we want to make sure that we have used a right locator to identify an element. For this purpose, we can highlight that element before applying any operation on that. In this way, we will be sure that we are targeting a right element.
There is no direct way in selenium webdriver to highlight any element. But, we do have Javascript Executor class which we can use to highlight any element through javascript.

Highlight an Element using Selenium Web Driver

See the code below. Language used is C#
IWebDriver driver = new FirefoxDriver();

var element = driver.FindElementById('txtuser');

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

js.ExecuteScript("arguments[0].style.border='3px solid red'", element);
we can go one step further and make it a function.
 public static void HighlighElement(this IWebDriver driver, IWebElement element)
        {
           IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

           js.ExecuteScript("arguments[0].style.border='3px solid red'", element); 
            

        }
Please note that above is an extension method. So this function will be available across every instance of webdriver.
To use this function in our code, we can use it like this with any webdriver instance.
IWebDriver driver = new FirefoxDriver();

var element = driver.FindElementById('txtuser');

driver.HighlighElement(element);
I hope this post helps you in automating your web application.
Please do leave your feedback in comments section.

No comments:

Post a Comment

Testing Challenge

Can you find more than 20 defects in the below image? Write your defects in the comments section.