How to access a Selenium element using JavaScriptExecutor

My task involves working with a collection of elements in Selenium, specifically located using the By.CssSelector method:

var contentRows = new List<TableRow>();

for (var i = 1; i < PositiveInfinity; i++)
{
    var cssSelectorToFind = $"tbody > tr:nth-child({i})";
    var bySelector = By.CssSelector(cssSelectorToFind);

    var rowElement = WebElement.FindElements(bySelector).ToArray();

    if (rowElement.Length == 1)
    {
        var description = $"{Description} Content row: {i}.  Selected by: {bySelector}.";

        var tableRow = new TableRow(bySelector, WebDriver, description, Headers);

        contentRows.Add(tableRow);
    }
    else
    {
        if (rowElement.Length == 0)
        {
            break;
        }
        else
        {
            throw new InvalidOperationException($"The selector {bySelector} returned more that one row at the same ordinal position.  Should be impossible... Best look at the selector and the HTML.");
        }
    }
}

return contentRows;

Now, I am looking to add a class of selected to each of these rows in the HTML.

I have knowledge that this can be achieved using the JavaScriptExecutor.

  • Is there a method to access each row individually for applying this class?
  • Do I need to assign a unique ID to each row and utilize it in JavaScript?

Answer №1

If you are looking to manipulate elements using JavaScript in Selenium WebDriver, you can pass IWebElement references as parameters to the ExecuteScript method. This allows you to interact with the element directly in your JavaScript code. For instance, if you want to highlight an IWebElement by drawing a red border around it, you can achieve this using the following code snippet (inspired by responses on this thread):

var element = driver.FindElement(By.Name("..."));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.border='3px solid red'", element);

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 capture screenshots of unsuccessful test cases when using Selenium WebDriver in Java?

Seeking assistance with saving screenshots to a specific folder on Mac while executing selenium webdriver automation scripts using Java. Can anyone provide guidance? Note: Due to the static declaration in my code, I am unable to utilize the following code ...

Executing tests simultaneously by class using both TestNG and Selenium with the Page Object Model (POM) design pattern

Currently, I am implementing webdrivermanager along with driver call. However, the pom pattern is maintained and it becomes complex to build in parallel using the threadlocal class. The structure of my module is as follows: A snippet of my code. Driver ...

Inject additional information following user authentication

Hello there! I have successfully developed a REST API using Node.js and StrongLoop, along with an Angular.js based app. After a user logs in, the server sends an accessToken which is stored in cookies. For every request, the accessToken is sent and verif ...

Exploring the potential of jQuery and AJAX for dynamic content generation:

I have developed a jQuery plugin that pulls data from a JSON feed (specifically YouTube) and then presents the results in a DIV. Everything is working well until I need to display the results with different configurations, such as more videos or from anoth ...

Ensure that a function completes before moving on in JavaScript

I am attempting to modify the save method so that it waits for this.collection.create() to complete before running, in order to prevent a potential crash. class UserRepository extends BaseRepository<User> { constructor() { super(); ...

The error message "Unsupported browser: chromedriver.exe" is thrown by SeleniumLibrary in Robot Framework

I encountered an issue while automating a login scenario using Robot framework with Python. The first test case in the suite failed due to lack of support for chrome/gecko driver. We have completed all installations and set the webdriver paths for geckodr ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

Encountering TimeoutException or ElementNotInteractableException when attempting to login to a website using Selenium

Encountering a login issue with the website (memodo.de/login) due to uninteractable login form. My code triggers either a timeout exception or an ElementNotinteractable Exception. Providing the HTML code for the website along with my current code below. A ...

What causes the intersection observer handler to not trigger when using scrollTo or scrollIntoView?

When an intersection observer is added to an element, it triggers the handler function when scrolled past a specific point. However, if the element is scrolled past that point using a button click, the handler does not get triggered. Is there a way to man ...

Unable to upload file in angular2 due to empty Body (FormData)

Attempting to upload a photo with Angular2 to my REST Service (Loopback). The Loopback service has been successfully tested using Postman and is able to accept files with the x-www-form-urlencoded header. Below is a simplified version of the service metho ...

Guide to displaying a local HTML file in CKEditor 4.3 using jQuery

Using CKEditor 4.3 on my HTML page, I aim to import content from a local HTML file and display it within the editor. (My apologies for any English errors as I am Brazilian :P) The jQuery code I have tried is as follows: $(document).ready(function(){ ...

Exploring the retrieval of stored information from $localStorage within an AngularJS framework

I have been working on a MEAN app, and after a user successfully logs in, I want to save the returned user data in the localStorage of the browser for future use. I am using the ngStorage module for this purpose. Below is the code snippet from my LoginCont ...

Add Text to HTML and Delete Added Content Upon Button Click

I have successfully implemented code that appends new content to the div "users". However, I am facing an issue with removing the appended content when a user clicks a button. Currently, the code only removes the "remove" button upon clicking. But I need ...

Using AngularJS to dynamically populate a dropdown menu from a JSON object

I am a beginner to Angular and currently facing my first significant challenge. The JSON object below is the address data retrieved from a third-party API and added to $scope.AddressData in a controller: $scope.AddressData = [{ "Address1":"South Row", ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...

Is there anything resembling 'Spread' and 'allSettled' in node with Q?

In my experience with Q, I have found the Q.allSettled function to be incredibly useful for handling arrays of promises, especially when needing to manage failure cases without using a specific fail handler. Currently, I find myself needing to utilize the ...

The error message "Uncaught TypeError: Cannot read property 'length' of undefined" is commonly encountered in asp.net while using dataTables with zero config

I am encountering an issue with dataTables in my ASP.NET webforms application. The table is generated in the codebehind at Page_Load() and works fine on other pages, but for some reason, I am getting an error message on one specific page: "datatables.min.j ...

Encountering installation issues with npm for bcrypt installation due to a

While working on an Express JS project, I encountered issues trying to install the bcrypt module for data authentication. Despite multiple attempts, I kept receiving the same errors. [email protected] install /media/iron/1d6c195f-2350-423c-a3f0-050 ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

The height of the iframe with the id 'iframe' is not functioning as expected

I am trying to set the iFrame's height to 80% and have an advertisement take up the remaining 20%. Code <!DOCTYPE html> <html lang="en"> <head> </head> <body> <iframe id="iframe" src="xxxxxx" style="border: ...