Encountering an error message stating 'click' property is undefined when implementing Java Script Executor in Selenium

I encountered an issue:

Cannot read property 'click' of undefined

when attempting to click a button using JavaScript executor. Despite trying multiple approaches such as action classes and WebDriverWait, I have been unable to successfully click the button. The JavaScript works in the console, but when integrated into my code, I receive this error.

The structure of the HTML DOM is as follows:

<div>
    <a class="button button--new-resource" href="/admin/certificate_types/new">
        <img src="/assets/icon-add-user-e2a98953aa1855b15304eb16415b536ee92e579ce89f429bcdd062faa855e261.svg" alt="Icon add user"> New Certificate Type
    </a>
</div>

Here is my Selenium script:

JavascriptExecutor js=(JavascriptExecutor) driver;        
js.executeScript("var x= document.getElementsByClassName('button button--new-resource')[0];"+"x.click();");

Answer №1

When encountering this error message...

An issue has arisen where the 'click' property cannot be read as it is undefined.

This problem suggests that the click() method cannot be executed because the WebElement has not fully loaded within the DOM Tree and remains in an undefined state.


Further Insights

Your statement about the "JavaScript working in console" indicates that the JavaScript functionality is fine. The actual issue lies in the WebElement not being fully rendered within the HTML DOM.


Possible Fix

To address this, it is recommended to utilize WebDriverWait for the

visibilityOfAllElementsLocatedBy()
method and select from the following Locator Strategies:

  • Using cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(".button.button--new-resource")));
    ((JavascriptExecutor) driver).executeScript("var x= document.getElementsByClassName('button button--new-resource')[0];"+"x.click();");
    
  • Using xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@class='button button--new-resource']")));
    ((JavascriptExecutor) driver).executeScript("var x= document.getElementsByClassName('button button--new-resource')[0];"+"x.click();");
    

Recommended Approach

In order to click on the element efficiently, it is suggested to apply WebDriverWait for the element_to_be_clickable() function and choose one of the below Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.button.button--new-resource[href='/admin/certificate_types/new']>img[alt='Icon add user']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='button button--new-resource' and @href='/admin/certificate_types/new']/img[@alt='Icon add user']"))).click()
    
  • Note: Ensure you import the following:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Answer №2

If you try to pass an element into the JSExecutor without combining it with a FindElement call, you are doing it the wrong way. This can lead to the script being executed before the element is found, resulting in an 'undefined' error.

// Find the element
var element = new WebDriverWait(driver, 20).until(ExpectedConditions.ElementToBeClickable(By.xpath("//*[@class='button button--new-resource']")));

// Click on the element that you have found
((JavascriptExecutor)driver).ExecuteScript("arguments[0].click();", element);

Answer №3

the issue lies within the quotation marks

js.executeScript("document.getElementsByClassName('button button--new-resource')[0].click();");

this should solve the problem

if there happens to be only one button

<a class="button button--new-resource" href="/admin/certificate_types/new">

try using document.getElementByClassName without specifying an index:

js.executeScript("document.getElementByClassName('button button--new-resource').click();");

Answer №4

The locator provided is incorrect, as it is a multi-class element and requires the use of '.' instead of a space.

js.executeScript("var x = document.getElementsByClassName('button.button--new-resource')[0];" + "x.click();");

Answer №5

What is the purpose of using JavaScript executor? Check out this example

WebElement element = driver.findElement(By.id(ID_NAME));
element.click();

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

Sending a variable to a VueJS component

I'm looking to pass a variable down to a component in my current setup. Here's the structure: Main: Meet.vue <html> <div class="carousel-cell"> <Category :searchTerm="woman"></Category> </div> <div cla ...

encountering issue alerts when using the MUI TextField module alongside the select function

Encountering an error in the MUI console: children must be provided when using the TextField component with select. <TextField select id="outlined-basic" label="User Name" name="user" size="small" {...teamForm.getFieldProps("user")} erro ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Fetching data from local JSON file is being initiated twice

I need some help understanding why my code is downloading two copies of a locally generated JSON file. Here is the code snippet in question: function downloadJson(data, name) { let dataStr = 'data:text/json;charset=utf-8,' + encodeURICompo ...

Why does the old component of the router still receive and handle events when <router-view/> changes?

Ugh... I need to explain a tricky situation I'm facing. I have a parent component that has two children listening for the same event and performing similar actions (see code snippet below): mounted() { EventBus.$on('edit', (data) => { ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Unable to execute or troubleshoot any test using selenium

Whenever I attempt to run or debug a test from my project's "class library", nothing seems to happen. No matter which test I run, there is no response. view image here ...

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

React form submissions result in FormData returning blank data

I am having trouble retrieving the key-value pair object of form data when the form is submitted, using the new FormData() constructor. Unfortunately, it always returns empty data. Despite trying event.persist() to prevent react event pooling, I have not ...

Updating the innerHTML of a frameset

I have a unique challenge that involves loading the frameset of www.example.com/2.html when accessing www.example.com/en/test/page.html. Successfully accomplished this task. Now, after loading 2.html in the frameset, I want to modify ".html" to ".html" t ...

Unusual HTML Structure (content misplaced or out of order?)

Recently, I started learning CSS/HTML in school and we just delved into Javascript. Currently, we are working on a website project. However, while trying to integrate the content with the navbar, I encountered a strange issue. When resizing to 620px or le ...

Having trouble sending information to a servlet with jQuery

As I work on developing an application utilizing jquery in conjunction with servlets, I have integrated the jquery theme roller for enhancing the interface on my Login.jsp page. <script> $(document).ready(function() { $("#dialog").dialog(); }); ...

Executing HTTP POST requests in Zend/PHP to interact with controller and mapper PHP classes

For our Android app to save data in MySQL, we need to make a POST request to a server running PHP Zend. Our supervisor has instructed us to create a class that follows the Zend MVC structure, specifically: GcmUsersController.php class GcmUsersController ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

Toggle the class of a div when clicked and then change the class of another div

In my website, I have a site overlay Div (#site-overlay) that is currently set as display:none. I am looking to change the class to block when I hover and click on the menu buttons. I can use both vanilla JavaScript and jQuery to achieve this. The menu it ...

Looking for a way to incorporate an image source property into a larger image?

I am working on a function that will enlarge an image when clicked on from a selection of 5 or more available images. The idea is that clicking on a small image will trigger the display of a larger version of that image in a frame. Here is an example of t ...

Element not found by Selenium as the page loads on a smaller screen

While developing our web application, I created a Selenium script that runs smoothly on my office workstation with a large screen. However, when I attempt to run the same script on my laptop, which has a smaller screen, it struggles to locate certain elem ...

Is it possible to switch the summernote editor between airmode and toolbar mode?

Currently, I am working on creating a report editor that displays only one toolbar when multiple summernote WYSIWYG editor sections are used. My solution involves having the first section as a full editor and the other section in airmode. Below is the HTM ...

Tips on maintaining the color of the favorite / unfavorite button even after refreshing the page

I am currently developing a Laravel project that allows users to favorite and unfavorite books. When a user clicks on the favorite button, the color changes to red. If clicked again, the color reverts back to gray. The database successfully updates without ...

Spring does not perform validation on JSON requests

Whenever I make the following request: "Person": { "name": 5 } The request will fail as it is a bad request since 5 is not a string. It displays: Person{name='5'}. Similarly, no error occurs when null is sent. The annot ...