Guide on utilizing JavaScript to modify the attribute of a chosen web element with Selenium WebDriver in Java

I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage.

After some research, I have discovered two methods for achieving this with Javascript:

Method 1

   WebDriver driver; // Assigned elsewhere
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("document.getElementByID('//id of element').setAttribute('attr', '10')");

Method 2

WebElement element = driver.findElement(By.id("foo"));
    String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);

However, my challenge lies in applying Javascript to a specific WebElement that I have located using Selenium WebDriver.

For instance, after selecting a link with Selenium WebDriver:

driver.findElement(By.linkText("Click ME"))

I now wish to set an attribute for this particular WebElement using Javascript.

I am unsure how to merge these two approaches and would greatly appreciate any guidance in finding a solution.

Answer №1

Similar to this:

JavaScriptExecutor js = (JavascriptExecutor) driver;
WebElement clickElement = driver.findElement(By.linkText("Click Here"));
js.executeScript("arguments[0].setAttribute('value', '10')",clickElement);

Answer №2

I encountered a similar issue and tackled it using the JavaScript Executor.

In my scenario, I had a list of elements where I needed to modify a specific property. First, I located the element, iterated through the list, created a JavaScriptExecutor object, and then applied the script to that individual element.

//arguments[0] refers to the element
//arguments[1] refers to the property
//arguments[2] refers to the new value of the property

List<WebElement> unselectableDiv = driver.findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));

for (WebElement element : unselectableDiv) {

    // System.out.println( "**** Checking the size of div "+unselectableDiv.size());

    JavascriptExecutor js = (JavascriptExecutor) driver;

    String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";

    js.executeScript(scriptSetAttr, element, "unselectable", "off");

    System.out.println(" *****   check value of Div property " + element.getAttribute("unselectable"));
}

Answer №3

Based on the tests you've run with your code:

driver.findElement(By.linkText("Click ME"))

The content inside innerHTML appears to be set as "Click ME".

If you want to update the value to, for example, 10 in the innerHTML, you can utilize the executeScript() method from the JavascriptExecutor interface by following these steps:

  • By utilizing innerHTML:

    WebDriver driver;
    WebElement element = driver.findElement(By.linkText("Click ME"));
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse.executeScript("arguments[0].setAttribute('innerHTML', '10')", element);
    

It is recommended that you employ a WebDriverWait for the elementToBeClickable() function using this solution:

  • Using textContent:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Click ME")))
    ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('textContent','10')", element);
    

Resource

You can find further detailed discussions here:

  • Selenium Datepicker using JavascriptExecutor

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

Next.js allows you to create a single page that corresponds to the root path '/' as well as a dynamic route '/param'

I have a single-page website built with Next.js. The home page, which displays a list of products, is located at route / and the corresponding code can be found in pages/index.js. Each product has an id, allowing users to jump directly to it using /#produc ...

Transforming JSON data into Java objects is seamless with the JSON to Java Object Mapper that integrates smoothly with J2objc

Currently, I'm utilizing the org.json.* classes from the j2objc distribution for handling JSON objects in my DTO classes. The mapping between my DTO classes and JSON Objects is done manually at the moment. I am aware of GSOn and Jackson as other opti ...

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

Is there a way to resolve the issue of my localStorage getting overridden on page refresh?

I am currently working on a simple React app and encountering an issue with the localStorage. Whenever I refresh the page, the todo list stored in the localStorage disappears. How can I ensure that the todos remain visible even after a refresh? Any sugges ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Finding a problem in node.js

I have encountered a problem while creating a server game using node.js. I am seeking assistance to resolve this issue. Here is the specific problem: https://i.stack.imgur.com/FMlsL.png app.js: var express = require('express'); var app = expr ...

How can you rearrange the order of objects in an array to only include duplicates?

I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an additional condition. var ...

Bringing in a selection of functions as an object using ES6 imports

functions.js export const setA = () => {...} export const setB = () => {...} export const setC = () => {...} component.js import {setA, setB, setC} from 'functions' export class componentOne extends React.Component { constructor(p ...

Using Node JS to retrieve JSON data from index.html upon button click

I'm currently learning the ropes of Node.js and want to set up a server where users can navigate to http://localhost:8000/ and be directed to index.html. In that file, there's a button to access JSON data. I plan to download this JSON data onto m ...

Angular: Struggling with Parent Component not recognizing changes in Child Component

Currently, I am facing an issue with my shopping cart functionality. When the website first loads and a user does not have a saved shopping cart, they need to click "add to cart" before one is created. The problem lies in the fact that my app.component doe ...

Storing a group of IWebElements as a collection in C# with Selenium by utilizing the [FindsBy] attribute

I'm struggling with setting multiple IWebElements to a collection using the [FindsBy] attribute from OpenQA.Selenium.Support.PageObjects. Specifically, I am trying to store all "li" elements in an instance variable called "MyElements". HTML <ul c ...

What is causing express.js not to authenticate properly?

I'm currently in the process of developing a server application using node.js, which is up and running on localhost:8080. As I attempt to make a login request, I've encountered an issue where one method works while the other fails. My suspicion i ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

Developing components with jQuery

I have a JavaScript program that works perfectly when I use the following line of code: li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>"); However, if I change the above line ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Setting character limits within textareas based on CSS classes in a dynamic manner

I'm looking to develop a JavaScript function that can set text limits for multiple textareas at once using a class, allowing for flexibility in case specific textareas need to be exempt. However, I'm facing issues with my debuggers - Visual Studi ...

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

Efficiently extracting text data from extensive HTML documents using the BeautifulSoup library

Currently, I am utilizing a combination of Selenium and BeautifulSoup to manually navigate through a list of web pages and save the information. However, I am encountering some difficulties while attempting to utilize the find and findAll methods. If you ...