Returns the visible text for the element.

getText() will automatically wait for the element to be present (until the specified timeout). If the element is not found, an error is thrown which will cause the test to fail. Starting with v1.2 you can suppress element not found errors by specifying the suppressNotFoundErrors option.

Usage

.getText(selector, callback)
.getText(using, selector, callback)

Parameters

Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns

Type description
string The element's visible text.

Example

module.exports = {
  demoTest(browser) {
    browser.getText('#main ul li a.first', function(result) {
      this.assert.equal(typeof result, 'object);
      this.assert.strictEqual(result.status, 0); // only when using Selenium / JSONWire
      this.assert.equal(result.value, 'nightwatchjs.org');
    });

    // with explicit locate strategy
    browser.getText('css selector', '#main ul li a.first', function(result) {
      console.log('getText result', result.value);
    });

    // with selector object - see https://nightwatchjs.org/guide#element-properties
    browser.getText({
      selector: '#main ul li a',
      index: 1
    }, function(result) {
      console.log('getText result', result.value);
    });

    browser.getText({
      selector: '#main ul li a.first',
      timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present
    }, function(result) {
      console.log('getText result', result.value);
    });
  },

  demoTestAsync: async function(browser) {
    const result = await browser.getText('#main ul li a.first');
    console.log('getText result', result);
  }
}

W3C WebDriver spec