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

What is the best way to extract attribute values from a CodeIgniter calendar using the Ajax success result?

I am working with the codeigniter calendar to display events. Initially, when I generate the calendar and show each event, everything works fine. Each event can be displayed in a bootstrap modal based on the day that is clicked and passed to my controller ...

What is the method in JavaScript for a child function to trigger a Return statement in its parent function?

I have encountered a unique problem. I need to retrieve some data downloaded via ajax and return it, but neither async nor sync modes are fetching the data in time for the return. Is there a way to call the return from a child function to the parent func ...

Creating a dual-column checkbox design with CSS only

I'm working with a dynamically generated form element that can only be styled using CSS. I need help achieving a specific layout without making any HTML changes, except for the classes. The "element" and "formField" classes are common and cannot be mo ...

Is there a way to add a new Date to Spring Data MongoDB easily?

Is there a way to add a new Date using Spring Data MongoDB? Currently, I am using the following: User = new User(); user.setCreationDate(new Date()); mongoOperation.save(user); The issue with this approach is that it saves the user with the current tim ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

Which is the Better Choice for an MMO WebSocket Server: Node.js or C++?

Contemplating creating a live game using WebSockets for the web has been on my mind. With my knowledge of Node.js, it's tempting to develop it there. However, C++ appears to be the favored server language due to its speed. Would it be best to try bui ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...

Error message: The "spawn" function is not defined and is causing a TypeError to be thrown in

Having a bit of trouble here. I'm trying to make an async request using redux-thunk in my action creator, and the code looks like this: export const downloadFromYoutube = (download) => { console.log("Hello"); return dispatch => { va ...

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...

Solving layout issues / Techniques for determining element heights

This new question is in relation to my previous one: How to position relative elements after absolute elements I have updated the JsFiddle from that question to better represent my current HTML, which I unfortunately do not have a URL for at the moment. Y ...

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

Continuing a Sequelize transaction after a loop

I am facing an issue where the transaction in my chain of code is committing immediately after the first loop instead of continuing to the next query. Here is a snippet of my code: return sm.sequelize.transaction(function (t) { return R ...

Add a directive on the fly, establish a connection, and display it dynamically

Within my markup, I have a tag element called popup-window which is handled by a specific directive. If I wish to incorporate multiple similar widgets that can be displayed or hidden in various locations, I currently need to include all these elements dire ...

Tips for dynamically updating an HTML value with Javascript

Summary of My Issue: This involves PHP, JS, Smarty, and HTML <form name="todaydeal" method="post"> <span id="fix_addonval"></span> <input type="radio" name="offer" id="offer_{$smarty.section.mem.index+1}" value="{$display_offe ...

Transform an { Key : Value } Object into Regular Variables using jQuery

Here is a code snippet in PHP: foreach($myarray as $key=>$value) { ${$key} = $value; } Now, I am wondering if we can achieve the same functionality using JS/jQuery? In this jQuery example, I am trying to assign the value of each td element with a cla ...

When accessing the webpage directly, WebDriver is able to locate elements that it was previously unable to find

Streamlining: Reserving bus ticket automatically Issue encountered: The WebDriver is not able to find the elements when I navigate to the webpage (passengerDetails) However, when I directly visit that page (passengerDetails), it successfully finds ...

Enhance Your jQuery Skills: Dynamically Apply Classes Based on URL Like a Pro!

Here is an example of HTML code for a progress meter: <div class="col-md-3" style="margin-left: -20px;"> <div class="progress-pos active" id="progess-1"> <div class="progress-pos-inner"> Login </div> </di ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Guide on incorporating geolib into React Native for distance calculation of two locations

Is there a simple way to calculate the distance between Longitude and Latitude in react native? I have the coordinates of my current location and destination, but keep encountering errors when attempting to use geolib for this calculation. I attempted to ...