Retrieve the value of an attribute for a given DOM element.

getAttribute() 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:

.getAttribute(selector, attribute, callback)
.getAttribute(using, selector, attribute, callback)

Parameters:

Name Type description
using
Optional
string

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

selector string|object

The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies element properties.

attribute string

The attribute name to inspect.

callback function

Callback function which is called with the result value; not required if using await operator.

Returns:

Type description
* The value of the attribute

Example:

module.exports = {
  demoTest(browser) {
    browser.getAttribute('#main ul li a.first', 'href', function(result) {
      console.log('result', result);
    });

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

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

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

W3C WebDriver spec: