Navigate through the rows and columns of an HTML table by utilizing Javascript with webdriver, specifically for Protractor in a non-angular environment

I need help with iterating through rows and columns using Selenium Webdriver. I am currently using Protractor for a non-angular web page. I have some Java code that works with the WebElement class to get the number of links, but now I need to transition this to JavaScript.

Any guidance on how to accomplish this would be greatly appreciated. Thanks, Sakshi

Answer №1

This solution worked for me:

driver.findElement(by.id('table_id')).then(function(table){
    table.findElement(by.tagName('tbody')).then(function(tbody){
        tbody.findElements(by.tagName('tr')).then(function(rows){
            for(i=0; i<rows.length;i++)
            {
                rows[i].findElements(by.tagName('td')).then(function(cols){
                    expect(cols[2].getText()).toMatch('ok');
                });

            }

        });
    });
});

Appreciate the help, Sakshi

Answer №2

const sampleData = [
    ['first row, first cell', 'first row, second cell', 'first row, third cell'],
    ['second row, first cell', 'second row, second cell', 'second row, third cell'],
    ['third row, first cell', 'third row, second cell', 'third row, third cell'],
];

// Loop through rows
$$('tr').each(function(rowElement, rowIndex) {
    // Loop through columns
    rowElement.$$('td').each(function(cellElement, colIndex) {
        // Compare cell content with test data
        expect(cellElement.getText()).toContain(sampleData[rowIndex][colIndex]);
    });
});

Answer №3

If you're looking for an easy solution, consider using xpath.

browser.driver.findElement(by.xpath("//table[@id='table_id']/tbody//tr")).then(function(rows){
  //your code...
  for(i=0; i<rows.length;i++){
    rows[i].findElements(by.tagName('td')).then(function(cols){
       expect(cols[2].getText()).toMatch('ok');
    });
  }
})

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

The element type provided is not valid: it is expected to be a string (for built-in components) or a class/function (for composite components) but instead it is undefined. This error

I am encountering an error of Element type is invalid: expected a string (for built-in components) or a class/function (for composite components). It seems like I may have forgotten to export my component from the file it was defined in, or there could be ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

Pagination Component for React Material-UI Table

I am interested in learning about Table Pagination in React UI Material. Currently, my goal is to retrieve and display data from an API in a Material UI Table. While I have successfully implemented some data from the API into the Material UI Table, I am ...

Checking to see if an object is null using Javascript/AngularJS

Below is the code snippet: function getBestBlock(size){ var bestBlock = {}; var blockEnteredTest = true; for(var i = 0; i < $scope.blocks.length; i++) { if($scope.blocks[i].state == "Free") { i ...

What is the best way to send a string without using quotation marks as a parameter in a function?

If I have an API that takes the query as http://localhost:8000/api/v1/rental/?place__startswith=kathmandu, how can I implement a generic search in ReactJS? What I attempted to do is pass the default parameter as search(query=kathmandu) so that the result ...

Steps to transfer the angularfire log in object to a service file

I am looking to enhance the usage of the logged-in object across my site. I am interested in moving this object to a service so that I can efficiently check for user authentication. Below is my login controller: .controller('LoginCtrl', function ...

In TypeScript, the choice between using `private readonly` within a class and

I have been contemplating the best method and potential impacts of referencing constants from outside a class within the same file. The issue arose when I was creating a basic class that would throw an error if an invalid parameter was passed: export cla ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

Is it possible to access a nested web element within another web element?

Hey there, do you have a passion for web elements? I am curious to know if it's achievable to locate a specific web element using classes, IDs, or other selectors, and then search within that element to find another element by its class. Situation ...

What is the best approach to determine the value of a textbox in an array for each row of

I am trying to display the total sum of values for each row in a data array. There are 5 rows of data, and I need to calculate the results for each one. Can someone assist me in solving this? function calculateTotalValue(){ var total = (document.get ...

Using the filter function in JavaScript to retrieve specific data

When the user_id from two different data sources matches, I need to return the email from the first source. The first source is a table in PostgreSQL called "results" and the second source is JSON data. I attempted this code snippet: var table = db.query ...

Can the month dropdown in react-datepicker be modified to display numbers instead of names?

Here is the code I have: <DatePicker selected={value?.toDate()} onChange={(date) => this.handleMonthChange(date)} inline showMonthYearPicker dateFormat={this.props.formatString} /> https://i.sstatic.net/SkdGP.png I am seeking ...

How can one retrieve every element within nested associative arrays?

Situation : Upon receiving a JSON array from a jQuery <-> PHP Ajax request, the unparsed JSON array structure appears as follows: {"Focus":{"id":2,"brand":"Ford","name":"Focus"}} Upon using JSON.parse(json);, the structure transforms to: Foc ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

The process of filtering a model stops at the third character and results in an empty output

Whenever I input a value into the 'temp_dollars' model and use a watch property to filter it, the input only retains the first 3 characters and resets. For instance: When I type 123, The model value remains as 123. But wh ...

The error message 'mainController' is not recognized as a function and is undefined, version 1.4

When it comes to utilizing newer angular directives like ng-blur, ng-focus, and form validation, the examples abound. They typically perform well in a standalone page or interactive coding platforms like plinkr and jsfiddle. However, there's one commo ...

Can you explain the distinction between the GenerateSW and InjectManifest choices within the vue ui pwd configuration?

Currently utilizing @vue/cli for building a vue project. I have initiated vue ui to access the vue UI and am in the process of customizing various available options. https://i.sstatic.net/h77AE.png Within Configuration -> PWA, I have come across the a ...

"Ionic 3: Utilizing the If Statement within the subscribe() Function for Increased Results

I added an if conditional in my subscribe() function where I used return; to break if it meets the condition. However, instead of breaking the entire big function, it only breaks the subscribe() function and continues to execute the navCtrl.push line. How ...

Expand or collapse Angular Material Accordion depending on selected Radio button choice

Is it possible to use a mat-accordion with radio buttons where each panel expands only when its corresponding radio button is selected? I have the radio buttons functioning correctly, but the panels are expanding and collapsing with every click rather than ...