getAttribute() method in Selenium WebDriver – Why, What and How to use?

Selenium WebDriver provides an important method named “getAttribute(String attributeName)“. In this post, we will learn below topics:-

  1. What is getAttribute() method?
  2. Why we use 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-classProperty is a representation of an attribute in the HTML DOM ( Document Object Model ) 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 text area 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 check points. For an 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 may need to fetch attribute (It may be color or back ground color) value through script and based on value we need to perform assertions or further actions.

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 current value of the given attribute as a String of the Web element. For example:- If we pass “class” as an attribute to getAttribute() method, it will return the value of “class” attribute. E.g. String classValue = ele.getAttribute(“class”)

I have used CURRENT word above. Actually value of attribute may change as well. So it will always return current value of attribute. When we call getAttribute() method for an attribute, it always looks for property with same name. If it finds property, it return the current value of it. If property is not found then it looks for attribute and returns value. If neither is found, it returns null.

As per Javadoc of Selenium WebDriver:-

“Get the value of the given attribute of the element. Will return the current value, even if this has been modified after the page has been loaded. 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.”

There are another two important points about this method:-

  1. getAttribute() method will return either “true” or null for attributes whose value is Boolean. E.g. async, autofocus, autoplay, checked etc.
  2. 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:-


Above web element (input tag) has many attributes. For e.g. maxlength, name, autocomplete etc. We can retrieve values for these attributes 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 an 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 have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

3 thoughts on “getAttribute() method in Selenium WebDriver – Why, What and How to use?

  1. Great Job Amod.Very few have the helping hand to others,your blog is amazing for both freshers and experienced.I suggested to few beginners to refer this portal.

Leave a Reply

Your email address will not be published. Required fields are marked *