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

Storing notes using HTML5 local storage

I recently developed a unique note-taking web application where users can create multiple notes and switch between them using tabs on the left side. My next step was to implement local storage for saving these notes, so I inserted the following code: $(d ...

Selecting items from a list at random using the power of math.random() and math.floor()

When attempting to randomize the popping of elements in a list stored in the baby variable, only baby[1] is being popped. How can I make it pop random elements? <body> <h1 id="1">bebe</h1> <h1 id="2">t ...

What are the potential drawbacks of directly modifying the state in ReactJS?

According to the documentation, it is stated that An example provided explains how directly modifying state will not re-render a component: // Incorrect this.state.comment = 'Hello'; Instead, the correct way is to use setState(): // Correct ...

Troubleshooting Issue: XMLHttpRequest Incompatibility with Internet Explorer

I'm having an issue with the script below. It works fine on Firefox and Chrome but doesn't seem to work on IE. I've tried various solutions, including lowering the security settings on my browser, but it still won't work. function se ...

Error: Unable to locate elements due to a null XPath expression. This issue arises while attempting to input keys using a Method

Encountering an error when using Sendkeys in methods. public static void inputTask(String task) throws Exception { // Entering task name GUIFunctions.typeTxtboxValue(driver,By.xpath(ObjRepoProp.getProperty("inputTaskName_XPATH")),task); Thread ...

What is the best way to start tiny-slider automatically once the video has ended?

I am currently using the tns-slider plugin and have a setup with 3 slides (2 photos and 1 video). <div class='tiny-slider'> <div class='slide slide1'> <div class='video-slide'> <video id=&qu ...

Utilizing Ajax, Jquery, and Struts2 for File Uploading

Can someone please provide guidance on uploading files using a combination of Ajax, jQuery, and Struts2? I have searched through numerous tutorials online but haven't found a suitable solution yet. The goal is to trigger a JavaScript function when a b ...

Exploring Alternative Methods to Navigate Through Elements Using JQuery UI Autocomplete

After testing two different approaches: <div id = "team-search-container"> <label for="team-search" class = "text-center"> <input type = "text" id = "team-search"> </label> </div> With the following code sni ...

Combining JSON objects in Node.js

I am extracting data from my database and converting it to JSON format. However, I now want to merge all the JSON data into a single JSON object. I have attempted various methods, but due to my limited knowledge of JavaScript syntax, I have not been able ...

Unable to successfully transfer parameters from AJAX to PHP

I successfully utilized Jquery UI to update the position of my table. Now, I am trying to pass a parameter from AJAX to PHP in order to update my database with the current table position. However, I encountered an issue where I receive a TypeError: data=nu ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

Retrieving the IP address of the remote Selenium node where the test browser instance is operating

As someone who is new to selenium and C#, I have set up a selenium hub with 6 remote nodes connected to it for my automation framework in C#. During the test runs, I would like to log the IP address of each remote node that the tests are running on. Is th ...

Learn the process of fetching checkbox values using JavaScript with this snippet

Is it possible to retrieve the name of the selected checkbox values/labels from the following code: <input id ="abc" value="abeexch" type ="checkbox"> <input id ="nam" value="suns" type ="checkbox"> If a checkbox is selected, how can I obtain ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

Preserve a data point without causing any alterations

I am working with a device that continuously sends values until it is stopped. These values are then saved inside an array. deviceMonitoring( device2 ){ // In this function, I populate the arrayTimestamp and then copy the first value. this.arrayElement = t ...

Leveraging the power of the 'var' keyword in JavaScript when

I have a javascript code snippet that looks like this: var grade_type = document.getElementById("grade_type").value; gradesRef.set({ grade_type: firebase.firestore.FieldValue.arrayUnion(grade) }); However, when the data is stored i ...

Error code E11000 is indicating that a duplicate key issue has occurred in the collection "blog-api.blogs" where the index "id_1" is

Issue with Error E11000 duplicate key error collection: blog-api.blogs index: id_1 dup key: { id: null } Encountering an error when trying to insert data after initially inserting one successfully. Referencing the blogSchema.js: const mongoose = req ...

You can't retrieve a JSON object using Javascript

Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it corr ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

How to update JSON file on server using JavaScript

I am encountering an issue that has been discussed quite frequently. Despite trying various solutions, none have proven effective so far. The problem lies in my JavaScript file where I have some data that I need to append to an existing .json file on my s ...