Selenium JS how to get text of an element

I have searched for an answer, and this should be relatively easy but how do I go about grabbing the text from a populated table in a browser?

The "inspect" looks something like this:

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

Obviously there is more to the table than this, but I just want to be able to grab that piece of text?

would I do something like

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

because that does not work. Or since there are multiple elements in the table should I

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

I have tried both methods.

32 thoughts on “Selenium JS how to get text of an element”

  1. To extract the text The Text I want you can use either of the following Locator Strategies:

    • Using className:

      await driver.findElement(By.className("component-body-text").getText()
    • Using 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()

Leave a Comment