getAttribute() method in Selenium Java

getAttribute() is used to get the value of the attributes related to HTML, and this post will discuss the getAttribute() method of the WebElement interface in detail.

  • Method declaration – String getAttribute(String name)
  • What does it do? It accepts an attribute name in the argument and returns the value of that attribute. If the attribute is not found, then it will return null.

Attributes provide additional information about the elements, and all tags can have some attributes that provide more information about them. Attributes normally come in key-value pairs.

Like we have the type and id attribute on the input tag

<input type="text" id = "firstName">

Here type and id are the attribute keys, whereas text and firstName are their values, respectively.

Attribute name and value
Code Example

We will try to get the “name” attribute value of the first text field on this page.

Input text field element

We will use the id locator to locate the element and get its name and type attribute value.

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = driver.findElement(By.id("firstName"));
		System.out.println("Value of name attribute: " + element.getAttribute("name"));
		System.out.println("Value of type attribute: " + element.getAttribute("type"));

	}
}

Output –

Value of name attribute: firstName
Value of type attribute: text

So, we got the value of the attributes using the getAttribute() method.

Boolean Attributes

Some attributes are deemed to be “boolean” attributes, and the getAttribute() method will only return “true” or null for these attributes. Below is the list of such attributes –

async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, selected, truespeed, willvalidate.

Let’s look at an example using the checked attribute. We will be using one of the checkboxes on this page.

checkbox element

Here is our input tag for the selected checkbox.

<input type="checkbox" name="hiddenSelect" class="pt-1 pb-1 pr-2 pl-2" id = "firstSelect5" value="firstSelect5" checked="checked">

As far as we know about the getAttribute() method, if we get the value of the checked attribute using getAttribute(‘checked”), then it should return “checked” as its value because we have checked = “checked” in the input tag.

But as checked is a boolean attribute, so, element.getAttribute(“checked”) will return “true“.

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/Checkboxes");

		WebElement element = driver.findElement(By.id("firstSelect5"));
		System.out.println("Value of checked attribute: " + element.getAttribute("checked"));

	}
}

Output –

Value of checked attribute: true

Let’s dig deeper into getAttribute() method

We have talked only about the attribute of an HTML element and how we can fetch its value using the getAttribute() method, but there is more to the getAttribute() method –

getAttribute() method returns the value of the property with the given name if it exists. If the property doesn’t exist, the attribute’s value with the given name is returned. If neither exists, null is returned.

What we meant by this is getAttribute() method fetches the property’s value first, and only if the property value is not found that it goes and searches for the attribute value.

Now, you might wonder what the difference between a property and an attribute is. You can refer to this link for a better understanding of the same, but we have also written a part from there to help you understand the concept in a few lines.

In a nutshell, we can say that an attribute is related to HTML, whereas a property is associated with DOM. When the browser parses the HTML, it converts the HTML attributes to DOM properties.

So, for input tag –

<input type="text" id = "firstName"> 

type and text are the attributes.

When the browser parses the HTML, it will create a DOM property of the attributes, which can be read using input.type or input.id.

Please note that all HTML attributes are not converted to properties with the same name. E.g., class attribute is converted to the className property.

So, using getAttribute(“className”) will fetch you the list of classes on any HTML element because it will fetch the value of the property named className and not of an attribute.

Text field element
public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "C:\\Users\\MEHUL\\OneDrive\\Desktop\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = driver.findElement(By.id("firstName"));
		System.out.println("Value of className property: " + element.getAttribute("className"));
	}
}

Output –

Value of className property: pt-1 pb-1 pr-2 pl-2

We can see that the class list is printed in the output.

We would let you on in a little secret even if you wrote element.getAttribute(“class”) would also give you the desired results. Because getAttribute() method internally converts element.getAttribute(“class”) to element.getAttribute(“className”).

The What If scenarios

Q – What if we try to get the value of such an attribute that doesn’t exist?

Let’s use the same text field element we used earlier. And let’s try to get the value of an attribute named “ABC“, which doesn’t exist.

We will get null as a value for that attribute.

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = driver.findElement(By.id("firstName"));
		System.out.println("Value of abc attribute: " + element.getAttribute("abc"));

	}
}

Output –

Value of abc attribute: null
Q – What if we pass null as an attribute in the getAttribute() method?

We will get NullPointerException as illustrated by the below program.

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = driver.findElement(By.id("firstName"));
		System.out.println("Value of null attribute: " + element.getAttribute(null));
	}
}

Output –

java.lang.NullPointerException: null value in entry: name=null
	at com.google.common.collect.CollectPreconditions.checkEntryNotNull(CollectPreconditions.java:32)
	at com.google.common.collect.ImmutableMap.entryOf(ImmutableMap.java:176)
	at com.google.common.collect.ImmutableMap.of(ImmutableMap.java:133)
	at org.openqa.selenium.remote.RemoteWebElement.getAttribute(RemoteWebElement.java:134)
	at Demo.CodekruTest.test(CodekruTest.java:22)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
	at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
	at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
	at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
	at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
	at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
	at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at org.testng.TestRunner.privateRun(TestRunner.java:794)
	at org.testng.TestRunner.run(TestRunner.java:596)
	at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
	at org.testng.SuiteRunner.run(SuiteRunner.java:276)
	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
	at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
	at org.testng.TestNG.runSuites(TestNG.java:1063)
	at org.testng.TestNG.run(TestNG.java:1031)
	at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
	at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
	at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Q – What if we use the getAttribute() method on a null WebElement?

Here also, we will get a NullPointerException.

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = null;
		System.out.println("Value of name attribute: " + element.getAttribute("name"));
	}
}

Output –

java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.getAttribute(String)" because "element" is null
	at Demo.CodekruTest.test(CodekruTest.java:22)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
	at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
	at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
	at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
	at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
	at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
	at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
	at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at org.testng.TestRunner.privateRun(TestRunner.java:794)
	at org.testng.TestRunner.run(TestRunner.java:596)
	at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
	at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
	at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
	at org.testng.SuiteRunner.run(SuiteRunner.java:276)
	at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
	at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
	at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
	at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
	at org.testng.TestNG.runSuites(TestNG.java:1063)
	at org.testng.TestNG.run(TestNG.java:1031)
	at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
	at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
	at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Please visit this link to learn more about WebElement and its methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.