Obtaining the text from an element in Selenium using JavaScript

I've been trying to figure this out, and it seems like it should be a simple task, but how can I extract the text from a table displayed in a browser?

When I use the "inspect" tool, the code snippet looks something like this:

<tr role="row">
  <th class="component-body-text" colspan="1"role="columnheader">### The Text I want ###</th>

While there is more content in the table, my focus is solely on retrieving that specific piece of text.

Would a method similar to this work:

await driver.findElement(By.className('component-body-text')).getText(); 

Unfortunately, this approach didn't yield results. Should I consider handling multiple elements within the table instead:

const sample = await driver.findElements(By.className('component-body-text')); 
sampleText = sample[0].getText();

I have experimented with both methods, but haven't had success yet.

Answer №1

If you are looking to retrieve the text The Text I desire, there are various Locator Strategies you can employ:

  • Utilizing className:

    await driver.findElement(By.className("component-body-text")).getText();
    
  • Employing css:

    await driver.findElement(By.css("tr[role='row'] > th.component-body-text[role='columnheader']")).getText();
    
  • Using xpath:

    await driver.findElement(By.xpath("//tr[@role='row']/th[@class='component-body-text' and @role='columnheader']")).getText();
    

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

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Tips for assigning a class name to a variable element within a react component?

I am interested in dynamically adding classes to an element. While I am familiar with methods using html-dom and passing a JavaScript expression to className, I am seeking a different approach. Is there a way to add classes similar to pushing them to an ar ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

Testing with Saucelabs is hindered by the browser's popup dialog

While testing my web app on SauceLabs, I encountered an issue with IndexedDB. Previously, my tests ran smoothly but now they are getting blocked by a browser dialog message that states "" wants to: store files on this device", along with an Allow button. ...

Inquiries about the jQuery Button Timer

Currently experimenting with jQuery to create a timer. Everything seems to be in place and the Stop Timer button is functioning properly. However, I'm facing issues with the Start Timer and Reset Timer buttons as they are not working as expected. Seek ...

Filtering a table with a customized set of strings and their specific order using pure JavaScript

Recently, I've been diving into APIs and managed to create a table using pure vanilla javascript along with a long list of sorting commands that can filter the table based on strings. My goal is to establish an object containing strings in a specific ...

Identifying text within a paragraph using JavaScript regex, excluding any URLs mentioned

How can I use JavaScript on the client side to find a search term in a paragraph while excluding any matches that are part of a URL? I attempted to use the following regex but encountered an error: "A quantifier inside a lookbehind makes it non-fixed widt ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

How can I make the arrows work on a secondary slider with EasySlider1.7?

I finally managed to get 2 sliders working on my page after reading through several other tutorials. However, I am facing an issue with the Prev & Next arrows on the second slider as they don't seem to work properly. I inherited this page from someon ...

Running several Angular requests simultaneously can trigger failures in test cases

I am facing an issue with my Angular 1.5 application and Rails 4.0 backend. During testing, when a Staff member logs in, three queries are simultaneously sent to the backend causing errors. Strangely, this issue does not occur in the development environmen ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

ESLint flags a misuse of promises in my code that I believe is acceptable

This symbol table implementation includes a method that needs some adjustments: public getAllSymbols(type?: typeof Symbol, localOnly = false): Promise<Set<Symbol>> { const promise = super.getAllSymbols(type ?? Symbol, localOnly); ...

Obtaining a Row from a Grid with Selenium

Having recently started using Selenium/Katalon, I've encountered a problem with my script. Specifically, I'm receiving an "unable to locate element" error for the table element that I have specified. I suspect that I might be referencing the wro ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

JavaScript loop to target a specific item

My goal is to animate the correct div under each navigation item, rather than all of them with the "navItemUnder" class. You can see exactly what I mean by hovering over a navigation item in this codePen. I am looking for a solution to target only one lin ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Tips for displaying subtotal in a Vue application using Firebase Realtime Database

I am currently troubleshooting a method in my Vue app that is designed to calculate the total value of all items sold. Despite seeing the correct values in both the database and console log, the calculation seems to be incorrect. Could there be an issue wi ...