When attempting to use getElementsByClassName in Selenium, the js.executeScript function does not function as expected

Here is a method I have written:

public void delayToCapture(String methodGetBy, String key){
    /* List of methodGetBy:
     * 1. getElementById
     * 2. getElementsByTagName
     * 3. getElementsByClassName
     * 4. querySelectorAll
     */

    System.out.println("Excuteing javaScript...");              

    if(methodGetBy.equals("getElementById")){
        js.executeScript("setTimeout(function(){ document." +methodGetBy+ "('" +key+ "').setAttribute('style', 'display: none');},500);");
    }
    else if(methodGetBy.equals("getElementsByClassName")){
        js.executeScript("setTimeout(function(){"
                        + "var elems = document.getElementsByClassName('"+ key +"');"
                        + "for(var i = 0; i < elems.length; i++){"
                        + "elems[i].style.display = 'none';}"
                        + "},"
                        + "500);");
    }

}

Now, let me show you how I call that method in another class:

delayToCapture("getElementsByClassName", "positionmenu");

Every time I run the code, the console displays this error message:

java.lang.NullPointerException

However, the interesting part is that when I directly run the following code in the browser console, it works perfectly fine:

setTimeout(function(){
var elems = document.getElementsByClassName('positionmenu');
for(var i = 0; i < elems.length; i++){
elems[i].style.display = 'none';
}
},500);

So, can someone please enlighten me on what might be causing this issue?

Answer №1

Consider implementing the following solution:

 else if(methodGetBy.equals("getElementsByClassName")){
        List<WebElement> element = driver.findElements(By.className(key));  // Finding elements by class name
        js.executeScript("setTimeout(function(){"
                        + "var elems = arguments[0];"
                        + "for(var i = 0; i < elems.length; i++){"
                        + "elems[i].style.display = 'none';}"
                        + "},"
                        + "500);", element);
    }

I hope this information proves useful to you.

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

Unable to extract text from webpage using Selenium WebDriver

I am having trouble extracting the email address from the following webpage: Webpage URL: This is my code snippet: driver.navigate().to(URL); String Email = driver.findElement(By.xpath("//*[@id="site-canvas"]/div[6]/div[2]/div[1]/div/div[1]/div/table/tb ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

Using Selenium to locate elements within an Iframe following a modification in content

The Challenge I am dealing with an iframe that contains a form. Once the form is submitted, the content within the iframe changes based on the input information. I need to verify the elements and texts in the result as part of my testing process. Approac ...

Page is being redirected due to a 401 status code

Setting up authorization using AngularJS and angular ui router involves handling a 401 status code from the server when a user attempts to access a protected route. An HTTP response interceptor has been created to detect the 401 status code and redirect t ...

Exiting the modal/popup box is currently disabled

I am struggling to figure out why the modal box/pop up is not closing when I click 'x'. It seems completely unresponsive. Check out the JavaScript code below: var kite = document.getElementById("poptext"); var kitetwo = document.getElementById( ...

Can Dropdown Items Be Generated Dynamically?

In the realm of React development, I find myself in need of a specific number of dropdown menus for a particular project. Each dropdown menu is expected to offer multiple options for selection. Typically, I would employ a straightforward map function to ha ...

Using Javascript to parse a regular expression in a string

I am facing a challenge with a JavaScript string that contains contact information that needs to be filtered. For example, I want to mask any email or phone number in the message. I have attempted the following approach: function(filterMessage) { ...

What is the process for extracting the value of a checkbox generated through JavaScript?

I recently came across a helpful post on Stack Overflow that provided sample code demonstrating how to display multiple list of checkboxes dynamically on a dropdown list. The function in the code was exactly what I needed for my webpage. However, I encount ...

How come I am unable to expand a collection of objects using Zustand?

I am currently utilizing Zustand in a TypeScript Next.js application. Strangely, whenever I attempt to loop through my state object, I encounter a runtime error message. The structure of the damaged zone object for my car is as follows: const damagedZones ...

What is the best way to stop the browser from automatically redirecting to another page after submitting a form?

I am using an AJAX call to a method that returns JSON data. How can I retrieve and read the JSON response without being redirected to a new empty page? [HttpPost] public JsonResult Test() { return Json("JSON return test", JsonRequestBehavior.AllowGe ...

Using Java to load an SSL keystore from a resource file

When having the following configurations: System.setProperty("javax.net.ssl.keyStore", '/etc/certificates/fdms/WS1001237590._.1.ks'); System.setProperty("javax.net.ssl.keyStorePassword", 'DV8u4xRVDq'); System.setProperty("sun.security. ...

Issues encountered while scraping Instagram's web content using Selenium with Python

I am facing an issue with scraping images from an Instagram profile. Even after scrolling to the bottom of the page and extracting all "a" tags, I only end up getting the last 30 image links. It seems like the driver is unable to view the full content of ...

Effective approach for managing a series of lengthy API requests

I am developing a user interface for uploading a list of users including their email and name into my database. After the upload process is complete, each user will also receive an email notification. The backend API responsible for this task is created u ...

How to start TextToSpeech from a class that is not an Activity?

I created a helper class that includes the necessary methods for text-to-speech synthesis. However, I am struggling to initialize a TextToSpeech object without using getApplicationContext(). How can I go about initializing it? public class SpeechAssista ...

Guide on setting up a connection between a Spring Boot application and AWS DocumentDB

I am facing issues connecting my spring boot application to AWS DocumentDB. Can someone please help me identify where I might be making a mistake? pom.xml [Your modified pom.xml content goes here] DocumentDBConf.java [Your modified DocumentDBConf.java ...

The functionality of my website is currently experiencing difficulties when accessed through the Android UC Browser

My website, , is experiencing issues with product loading and the '+' button in the side menu not working on UC Browser. It works fine on other Android browsers like Chrome and Firefox, but I am confused as to why it is not functioning properly o ...

What is the best way to store this input in an Array?

Having trouble reading the SOP statement into an array for this SOP statement in Java. I'm very new to Java, so any help would be greatly appreciated. Attempted to place the SOP statement in this constructor: public class QuizScore { private in ...

The class responsible for serialization of keys was not located

While attempting to send an Array of JSON data to a Kafka topic using a Spring Boot application, the following error occurs: Error: org.apache.kafka.common.config.ConfigException: Invalid value org.apache.kafka.common.serialization.StringSerializer; for ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...