What is the method for fetching a WebElement with a specific CSS attribute using JavascriptExecutor?

Currently, I am faced with a situation in which I need to locate a WebElement based on its CSS property, specifically the background-color.

I successfully crafted the JQuery script below to pinpoint the element using the firefox console:

$('.search-bar-submit').each(function() { 
   return $(this).css('background-color') == '#fdd922'; 
});

https://i.sstatic.net/BjK6i.png

Subsequently, I proceeded to develop the code to accurately identify and click on this WebElement, namely the searchbox:

driver.get("http://www.flipkart.com/");
driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");

String query = "$('.search-bar-submit').each(function() { "
            + "return $(this).css('background-color') == '#fdd922'; });";
    
WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);
searchbox.click();

Upon executing the program, an error

Exception in thread "main" java.lang.NullPointerException
occurs at the line searchbox.click();

If anyone can assist me in finding the searchbox using JavascriptExecutor and then clicking on it, I would greatly appreciate it. Could there possibly be something trivial that I've overlooked?

Your help is highly valued. Thank you in advance.

Answer №1

To execute a script that retrieves a WebElement using JavaScript in Selenium, you can use the following code:

WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);

However, it's important to note that the above code doesn't return the result of the function call back to the caller. To ensure that the webelement is returned to the Selenium script (webdriver), add a "return" statement in the script.

return $('.search-bar-submit').each(function() { 
   return $(this).css('background-color') == '#fdd922'; 
});

It's essential to typecast the return type as List<WebElement>. If you typecast it incorrectly, for example, as an ArrayList, it will throw a ClassCastException since an ArrayList cannot be cast to a WebElement.

Here is modified code including proper handling and retrieval of the WebElement:

List<WebElement> searchbox = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(query);

for(int i=0;i<searchbox.size();i++){                     
    searchbox.get(i).click();
}

Explanation of EDIT:

The code may not work in Firefox due to differences in how the browser returns a JSON object of the webelement. Selenium has replaced its usage of org.json with Gson, which might cause compatibility issues with the response received from Firefox.

Solution:

We utilize JQuery's get function to retrieve the matched DOM Elements:

$('.search-bar-submit').each(function() { 
   return $(this).css('background-color') == '#fdd922';
}).get(0);

Code:

public class jquerytest {
    public static void main(String[] args) throws Exception {
        WebDriver driver = new FirefoxDriver();
        
        // Perform actions on the webpage
        // ...
    }
}

This tweaked code ensures correct execution on both Chrome and Firefox browsers. Feel free to ask if you need further assistance!

Answer №2

After running the code provided, everything seems to be working perfectly. The jquery also functions well, and I particularly enjoy the messages it prints to the console in the developer view (hahaha).

driver.get("http://www.flipkart.com/"); 
WebElement input = driver.findElement(By.id("fk-top-search-box"));
input.sendKeys("iphone");
WebElement element = driver.findElement(By.className("fk-font-bold"));
element.click();

It appears there may be an issue with the executeScript function, which should be corrected as shown below.

System.out.println(((JavascriptExecutor)driver).executeScript(query, driver));

Typically, when calling javascript, I format it like this to remove the windowed attribute so that a hyperlink opens in the same tab:

String href = linkObject.getAttribute("href");
href = href.substring(0, href.length()-10)+")";
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return arguments[0].href = \""+href + "\"", linkObject);  

However, when receiving JSON data back, WebDriver may have trouble understanding it. For more information on this issue, please refer to the following link:

As an alternative suggestion, you can use the following code to retrieve the background-color in rgba format:

WebElement button = driver.findElement(By.className("search-bar-submit"));
button.getCssValue("background-color");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The default value of the input color in HTML/NextJS does not update when changed

Issue: The color input does not change when the default value (#ffffff) is declared. https://i.sstatic.net/BpqUj.png However, it works normally if I don't declare a default value. https://i.sstatic.net/0dBd6.png Note: Using NextJS framework. <i ...

Troublesome behavior from Bootstrap's datepicker

Recently, I decided to dive into front-end development using Bootstrap but I'm facing some challenges. There are two issues here. The calendar glyph is appearing under the date input field instead of at the end of it on the same line. The picker is ...

Is there a way to obtain the full class name if only a portion of it is known?

I am trying to extract the complete classname of an element, but I only have partial information about it. <div class="anotherclass my-class-no-1 onemoreclass...">div> Currently, I can select the element using this: $([class*="my-class-no-"]... ...

When dynamically loading content with ajax, dynamic content fails to function properly

Currently, I am attempting to incorporate dynamic content loading after the user logs in by utilizing $.ajax. Here is how it's being done: $.ajax({ url: "functions.php", type: "GET", data: login_info, datatype: 'html', a ...

Rails : CSS/JavaScript functioning perfectly on local server, facing issues on Heroku deployment

My Rails website features various CSS animation effects and JavaScript elements. While these transitions function smoothly on my local environment, they do not work properly on Heroku. Examining the Heroku logs: 2013-09-17T17:13:36.081145+00:00 app[web.1 ...

Struggling with eliminating the bottom margin on your website?

I can't figure out where this mysterious margin is coming from in the CSS - there's a consistent 30px of space at the bottom of each web page. Any assistance would be greatly appreciated. I know it's probably something simple, but my brain ...

Identifying various device platforms through CSS styling

After extensive research and testing, I have explored a variety of resources and solutions for implementing device-specific CSS on my webpage. Here are some of the references I've studied: Detect iPhone/iPad purely by css Detect Xoom browser (Andro ...

Java provides multiple constructors with a single parameter of varying data types

I seem to be encountering an issue with constructors. public abstract class ShapeDrawer implements iShapeDrawer { protected SimpleLine line; // the line awaiting to be drawn protected SimpleOval oval; // the oval ready for drawing protected S ...

The HelloWorld program experiences difficulties functioning when implemented on Windows Azure

I've encountered an issue while trying to deploy a HelloWorld Application using Eclipse. While the program runs successfully in the Windows Azure emulator, I am unable to publish it in Windows Azure due to the error message: Failed uploading deploymen ...

Vuetify: how to disable the color transition for v-icon

My menu includes both icon and text items, with hover color styled using the following CSS: .v-list-item:hover { background: #0091DA; } .v-list-item:hover .v-list-item__title, .v-list-item:hover .v-icon { color: white; } The problem is that the ...

Error Occurs When Attempting to Access an Excel File in Selenium With Nullpointer Exception

Hey everyone, I've been searching everywhere for a solution to this issue but I just can't seem to find one. Why am I getting a Null Pointer Exception here? I'm not sure what's causing it. It seems like the path is correct, but it' ...

Styling tip: Distance the tooltip from its parent element when scrolling through a list

I have a table inside li tag, and I want to display the description on :hover inside td. However, when scrolling through the list, the description content starts to appear with a distance from its parent. Despite trying various combinations of position se ...

Automatically reset the form after submission in CakePHP 1.3

I've encountered an issue with my report form that is linked multiple times on a page to a jQuery dialog box. To prevent cross-posting, I added a random string to the submission process. After successfully submitting the form on a single page access, ...

Resizing Images Responsively Using Bootstrap

I'm working on specifying image sizes for different screen sizes. I'm wondering if there are any specific Bootstrap classes that only work at certain screen sizes. If so, it would be great because then I could use something like <img class = " ...

What is the best way to incorporate the .top offset into a div's height calculation?

Looking to enhance the aesthetic of this blog by adjusting the height of the #content div to match that of the last article. This will allow the background image to repeat seamlessly along the vertical axis. I attempted the following code: $(document).re ...

Remove the outline on a particular input and retain only its border

Even after trying to use "outline: 0", nothing seems to change. #input_field { outline: 0; width: fit-content; margin: auto; margin-top: 20%; border-radius: 30px; border: 2px solid turquoise; padding: 6px; } <div id="input_field"> ...

Java: Display a list of connected cameras

At the moment, my software is able to retrieve a list of drives connected to the computer using File.listRoots(). However, when I directly connect a camera or an MP3 player to the computer (instead of inserting a memory card), it does not appear in the lis ...

Discovering the Week by week commencement and conclusion dates utilizing angularjs

Previously, I was utilizing the angularjs-DatePicker from npm. With this plugin, I could easily select a date from the calendar. However, now I require two fields - FromDate and ToDate - to display the week StartDate and EndDate whenever a date within that ...

What is the best way to interpret HTML codes using Python and Selenium?

Looking to retrieve a link in an HTML path? Here is the code snippet: <div class="btn btn-primary btn-lg"> <a href="https://storage.googleapis.com/audiog-204018.appspot.com/files/hello1574358335.mp3"> Download MP3 </a> < ...

Unexpected issues have arisen with the $.ajax function, causing it

I am facing an issue where I can see the loader.gif but unable to view avaiable.png or not_avaiable.png in my PHP file. What could be causing this problem? $(document).ready(function()//When the dom is ready { $("#inputEmail").change(function() { ...