How to get data of attributes in JavaScript using Selenium

Are you looking for a way to get data of attributes in JavaScript with Selenium? Look no further! This guide will show you how to do it easily and quickly.

Guide Banner Image
Home Guide How to get data of attributes in JavaScript using Selenium

How to get data of attributes in JavaScript using Selenium

Knowing how to get attribute value in Selenium is essential for validating web elements during automation testing. By using methods like getText() and getAttribute(), testers can verify UI behavior, compare attribute data, and ensure applications function as expected across different browsers and environments.

Overview

What are Attributes in Selenium Testing?

  • Attributes provide additional information about HTML elements (e.g., id, class, src, style).
  • Types include required attributes (e.g., src in <img>), optional, standard/global, and event attributes (e.g., onclick).
  • In automation, fetching attribute values is crucial to validate UI behavior and data binding.

Methods to Get Attribute Value in Selenium with JavaScript

  • getText() → retrieves the visible inner text between HTML tags.
  • getAttribute() → fetches the value of a specific attribute (returns string, null, or boolean).
  • Example: element.getAttribute(“data-sku”) retrieves product metadata, while getText() validates the displayed product name.

Step-by-Step Guide to Retrieve Attribute Values

  • Set up project → install Node.js, Selenium WebDriver, ChromeDriver, and Mocha test runner.
  • Write test script → locate elements with By.id or By.className, then call .getAttribute() and .getText() for comparison.
  • Execute test → run npm test → console logs confirm whether attribute values (e.g., product image name) match UI text.

This article explains in detail what attributes are in Selenium, how to fetch their values using JavaScript, the steps to implement tests, and how to scale with Selenium Grid and BrowserStack.

What are Attributes?

Attributes are additional information added to the HTML tags that are used to adjust the behavior or display of an HTML element. There are many tags in HTML that can include attributes in them.

For example, <input type = “email”>, here the input tag has the attribute of type, which holds a value of email. In this example, an attribute is useful in clarifying what type of value must be put in the input element, i.e., email.

Here is the syntax of HTML elements containing attributes:

<element attribute="value"> content </element>

There are numerous attributes in HTML, used for several HTML tags, however, only a few are majorly used in automation testing. Some commonly used HTML attributes are id, class, src, style, etc.

Types of Attributes

HTML attributes are broadly classified under four categories:

  1. Required attributes: These are the types of attributes that are always required in HTML tags. Without these attributes, HTML tags are incomplete. For example, the <img> tag must have the src attribute.
  2. Optional attributes: As the name suggests, these are optional HTML attributes which are not necessarily needed to be added. However, when added, give more information about the HTML tag.
  3. Standard attributes: These are global attributes that function with almost all the HTML tags.
  4. Event attributes: These are the attributes that trigger an event when a user performs some actions against them. For example, onclick attribute on an element performs an event when a user clicks on the web element.

How to get data of attributes in JavaScript using Selenium

In this tutorial, let’s see two effective methods to get data of attributes in JavaScript using Selenium.

  • get_text method

Selenium introduced this method to get the inner text from a specific web element. It will return a string type value, a text which is not hidden by any CSS. It simply extracts the text between the tags.

  • get_attribute method

Where get_text method fetches the inner text, get_attribute retrieves the value of the given attribute. If there is no value present, it returns null. Also, it returns true and null for boolean values.

Steps to Get Data of Attributes using Selenium with JavaScript

Prerequisites

  • Node.js: Install the latest version of Node.js in your system. You can download it from its official website. Installing Node.js will automatically install the latest version of NPM.
  • IDE: IDE is used for writing your code; in this example, let’s use VS code to write our test code; however, you can use any IDE.

Step 1: Setting up the project

  • Navigate to your project folder and create a package.json file with the following command.
npm init
npm install selenium-webdriver
  • Now, install a browser-driver, to run tests on a browser. In this example, let’s use the Google Chrome web driver.
npm install chromedriver
  • To add node modules to your project, install mocha. Mocha will also be used here as a test runner.
npm install mocha
  • After performing the above installations, let us edit the scripts section in the package.json file.
“scripts”: {
“test”: “mocha –timeout 60000”
}

Step 2: Writing Test script

In this tutorial, let us use this sample website to learn to get data of attributes in Selenium. In this test, let us check whether the device has the correct image name attached to it. Therefore, you will have to take two attributes’ values and compare them if they have the device’s name in them.

Writing Test script

To get the attributes, right-click the webpage and proceed to inspect the element.

Create a JavaScript file and enter the following test script into it

var webdriver = require('selenium-webdriver');
const {By} = require('selenium-webdriver');

describe('Check device has correct image', function () {

var driver = new webdriver.Builder().forBrowser('chrome').build();

before(async function () {

await driver.get('https://www.bstackdemo.com/');

});

it('Check device matches with image name', async function(){

let attribute = await driver.findElement(By.id('1'));

let name = await driver.findElement(By.className('shelf-item__title'));

console.table([await attribute.getAttribute('data-sku') , await name.getText()])

});

after(() => driver.quit());

}

Step 3: Executing Test

To run the test, execute the following command.

npm test

After running the test, you will see a terminal like this, where both the values indicate that the image of the product matches the title of the product.

Executing Test

This tutorial explains some of the effective ways to get data of attributes in JavaScript using Selenium. The methods discussed above are not limited to JavaScript and can be used with any Selenium-supported language or framework. You can set up the project in the Localhost. However, you may use Selenium grid to broaden your automation testing experience. Selenium grid allows you to perform testing on multiple operating systems and browsers simultaneously. BrowserStack allows you to run Selenium tests on 3000+ real devices, browsers, and operating systems.

Run Selenium tests on Real Device Cloud

Tags
Selenium Selenium Webdriver

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord