Method 1: getAttribute(): Why, What and How to use?

Hello Folks,

In this post we will learn:

  1. Why we use getAttribute() method?
  2. What is getAttribute() method?
  3. How to use getAttribute() method?

We will see a lot of examples as well. Let’s start:-

Why we require getAttribute() method?

A web developer defines attribute and properties to a web element to add extra meaning to it. For example: I am a human and I have a name, height, length, color etc which are attributes and properties of mine.

There are slight difference between attribute and properties of web element.

  1. Attributes carry additional information about an HTML element and come in name="value" pairs. Example: <div class=”my-class”></div>. Here we have a div tag and it has a class attribute with a value of my-class. Property is a representation of an attribute in the HTML DOM tree. So the attribute in the example above would have a property named className with a value of my-class.
  2. Attributes are defined by HTML while Properties are defined by DOM.
  3. Some HTML attributes have 1:1 mapping onto properties. id is one example of such and some do not. For example: the value attribute specifies the initial value of an input, but the value property specifies the current value.
  4. Attributes are in your HTML text document/file, whereas properties are in HTML DOM tree. This means that attributes do not change and always carry initial (default) values. However, HTML properties can change, for example when user checks a checkbox, inputs text to textarea or uses JavaScript to change the property value.

For more details check this post.

So, during development of automation script, we need to retrieve values of attributes or properties of web element to verify test cases.

Example: Consider a movie ticket booking application. Color of available seat will be different from booked one. Available seat color will be green and booked seat color will be red. So, to check whether seat is available or booked, we need to fetch attribute (color) value through script and based on value we need to perform operations.

So to achieve this Selenium WebDriver provides a method called getAttribute().

What is getAttribute() method?

Syntax: java.lang.String getAttribute(java.lang.String name)

  • getAttribute() is method which is declared in WebElement interface.
  • It returns the value of the given attribute as a String of the Web element.
  • More exactly, this method will return the value of the property with the given name, if it exists. If it does not, then the value of the attribute with the given name is returned. If neither exists, null is returned.
  • getAttribute() method will return either “true” or null for attributes whose value is Boolean.
  • The following commonly mis-capitalized attribute/property names are evaluated as expected:
    • If the given name is “class”, the “className” property is returned.
    • If the given name is “readonly”, the “readOnly” property is returned.

How to use getAttribute() method?

getAttribute() method work on specific web element. So first you need to locate a web element and then you need to call getAttribute() method on it by specifying attribute for which value you require.

We will see examples now:

HTML code for search box of Google:


<input class="gsfi" id="lst-ib" maxlength="2048" name="q" autocomplete="off" title="Search" type="text" value="" aria-label="Search" aria-haspopup="false" role="combobox" aria-autocomplete="both" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; background: url(&quot;data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D&quot;) transparent; position: absolute; z-index: 6; left: 0px; outline: none;" dir="ltr" spellcheck="false">

Above web element has many attributes. For e.g. maxlength, name,  autocomplete etc. We can retrieve values for this attribute using getAttribute() method.

Java Code:


public class GetAttributeExamples {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
WebElement searchTextBox= driver.findElement(By.id("lst-ib"));
// retrieving html attribute value using getAttribute() method
String titleValue=searchTextBox.getAttribute("title");
System.out.println("Value of title attribute: "+titleValue);
String autocompleteValue=searchTextBox.getAttribute("autocomplete");
System.out.println("Value of autocomplete attribute: "+autocompleteValue);
// Retrieving value of attribute which does not exist
String nonExistingAttributeValue=searchTextBox.getAttribute("nonExistingAttribute");
System.out.println("Value of nonExistingAttribute attribute: "+nonExistingAttributeValue);
}
}

Output:
Value of title attribute: Search
Value of autocomplete attribute: off
Value of nonExistingAttribute attribute: null

Now let’s see some interesting point:

Run below code and observe output:


String classValue=searchTextBox.getAttribute("class");
System.out.println("Value of classValue attribute: "+classValue);
String classNameValue=searchTextBox.getAttribute("className");
System.out.println("Value of classNameValue attribute: "+classNameValue);

Output:

Value of classValue attribute: gsfi lst-d-f
Value of classNameValue attribute: gsfi lst-d-f

Above web element have attribute class whose value is “gsfi” but it is giving any other value. Actually it is giving value of property “className” which is given by DOM and see the last point under heading “What is getAttribute() method?”. You will understand the reason.

If you need to do something more precise, e.g. refer to an attribute even when a property of the same name exists, then you should evaluate Javascript to obtain the result you desire. I will explain in different post to retrieve attribute value using javaScript.

That’s it guys. I tried to explain every basic thing about getAttribute() method. Hope you must have learnt new things.

 

If you like my posts, please like, comment, share and subscribe.
Thank You.
#HappyLearning

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning