Get Attribute in Selenium
getAttribute() in Selenium is a WebElement method used to retrieve the value of an HTML attribute from a web element. It is commonly used when testers need to read values such as href, value, class, id, name, placeholder, title, src, and other attributes.
In Selenium WebDriver with Java, the getAttribute() method is provided by the WebElement interface and returns the requested attribute-related value as a String. It is especially useful when the required information is stored in an HTML attribute or when the test needs attribute-related DOM information.
JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, locators, web elements, TestNG, automation frameworks, data-driven testing, Page Object Model, cross-browser testing, and practical automation projects. You can learn more through the Selenium Training Course and register for a Selenium Course Demo.
1. What is getAttribute() in Selenium?
The getAttribute() method is used to retrieve the value associated with a specified attribute or attribute-related value from a WebElement.
Consider the following HTML:
<input id="username" name="user" value="admin" placeholder="Enter Username">
Selenium can retrieve the value using:
WebElement username = driver.findElement(By.id("username"));
String value = username.getAttribute("value");
System.out.println(value);
The output will be:
admin
2. Syntax of getAttribute()
The basic syntax is:
String value = element.getAttribute("attributeName");
Where:
- element represents the WebElement.
- getAttribute() retrieves the requested attribute-related value.
- attributeName is the name of the attribute to inspect.
- String value stores the returned value.
3. How getAttribute() Works
The getAttribute() method first requires Selenium to locate a WebElement. Selenium then requests the specified attribute-related value and returns it as a String.
Open Browser
↓
Open Web Page
↓
Locate Web Element
↓
Specify Attribute Name
↓
Call getAttribute()
↓
Retrieve Attribute Value
↓
Store or Verify Value
For example:
WebElement element = driver.findElement(By.id("username"));
String attributeValue = element.getAttribute("value");
System.out.println(attributeValue);
4. Simple Example of getAttribute()
Consider the following HTML:
<input id="email" value="[email protected]">
Selenium code:
WebElement email = driver.findElement(By.id("email"));
String value = email.getAttribute("value");
System.out.println(value);
Output:
[email protected]
5. Complete Selenium Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetAttributeExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com");
WebElement element = driver.findElement(By.id("username"));
String value = element.getAttribute("value");
System.out.println("Attribute Value: " + value);
driver.quit();
}
}
6. getAttribute() with ID
The id attribute can be retrieved from an element using getAttribute().
WebElement element = driver.findElement(By.name("username"));
String id = element.getAttribute("id");
System.out.println("ID: " + id);
Example HTML:
<input id="username" name="user">
Output:
username
7. getAttribute() with Name
The name attribute can be retrieved from a WebElement.
WebElement element = driver.findElement(By.id("username"));
String name = element.getAttribute("name");
System.out.println("Name: " + name);
Example:
<input id="username" name="userName">
Output:
userName
8. getAttribute() for Class
The class attribute can be retrieved using getAttribute().
WebElement element = driver.findElement(By.id("login"));
String className = element.getAttribute("class");
System.out.println(className);
Example HTML:
<button id="login" class="btn btn-primary">Login</button>
Output:
btn btn-primary
9. getAttribute() for Value
One of the most common uses of getAttribute() is retrieving the current value associated with an input field.
WebElement username = driver.findElement(By.id("username"));
String value = username.getAttribute("value");
System.out.println("Username: " + value);
Example:
<input id="username" value="admin">
Output:
admin
10. getAttribute() for Placeholder
The placeholder attribute can be retrieved to verify the hint displayed inside an input field.
WebElement email = driver.findElement(By.id("email"));
String placeholder = email.getAttribute("placeholder");
System.out.println("Placeholder: " + placeholder);
Example:
<input id="email" placeholder="Enter Email Address">
Output:
Enter Email Address
11. getAttribute() for href
The href attribute is commonly retrieved from links.
WebElement link = driver.findElement(By.linkText("Contact Us"));
String href = link.getAttribute("href");
System.out.println("URL: " + href);
Example HTML:
<a href="/contact">Contact Us</a>
The returned value represents the link destination associated with the href.
12. getAttribute() for src
The src attribute can be retrieved from images, scripts, or other elements containing a source URL.
WebElement image = driver.findElement(By.id("logo"));
String source = image.getAttribute("src");
System.out.println("Image Source: " + source);
Example:
<img id="logo" src="/images/logo.png">
13. getAttribute() for title
The title attribute can be retrieved from an element.
WebElement element = driver.findElement(By.id("help"));
String title = element.getAttribute("title");
System.out.println("Title: " + title);
Example:
<button id="help" title="Click for Help">Help</button>
14. getAttribute() for data-* Attributes
Modern web applications frequently use custom data-* attributes. These can be retrieved using getAttribute().
WebElement product = driver.findElement(By.id("product"));
String productId = product.getAttribute("data-product-id");
System.out.println(productId);
Example:
<div id="product" data-product-id="P1001">Laptop</div>
Output:
P1001
15. getAttribute() for aria Attributes
Accessibility-related attributes such as aria-label can also be retrieved.
WebElement button = driver.findElement(By.id("menu"));
String label = button.getAttribute("aria-label");
System.out.println("ARIA Label: " + label);
Example:
<button id="menu" aria-label="Open Menu">☰</button>
16. getAttribute() with CSS Selector
CSS selectors can be used to locate the WebElement before retrieving its attribute.
WebElement element = driver.findElement(By.cssSelector("#username"));
String placeholder = element.getAttribute("placeholder");
System.out.println(placeholder);
Another example:
String value = driver.findElement(By.cssSelector(".username")).getAttribute("value");
17. getAttribute() with XPath
XPath can be used to locate the element before calling getAttribute().
WebElement element = driver.findElement(By.xpath("//input[@id='username']"));
String value = element.getAttribute("value");
System.out.println(value);
Another example:
String href = driver.findElement(By.xpath("//a[@id='contact']")).getAttribute("href");
18. getAttribute() for Input Field Validation
Input values are frequently validated during Selenium automation testing.
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
String actualValue = username.getAttribute("value");
System.out.println("Entered Value: " + actualValue);
Output:
Entered Value: admin
19. getAttribute() with TestNG Assertion
getAttribute() can be combined with TestNG assertions to validate attribute values.
import org.testng.Assert;
String actualValue = driver.findElement(By.id("username")).getAttribute("value");
String expectedValue = "admin";
Assert.assertEquals(actualValue, expectedValue);
If the values match, the assertion passes. If they differ, the test fails.
20. getAttribute() for Login Form
In a login form, getAttribute() can be used to verify input values and attributes.
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
username.sendKeys("admin");
password.sendKeys("Admin@123");
String usernameValue = username.getAttribute("value");
String passwordValue = password.getAttribute("value");
System.out.println("Username: " + usernameValue);
System.out.println("Password: " + passwordValue);
21. getAttribute() for Checkbox
Checkboxes can contain attributes that provide information about their HTML configuration.
WebElement checkbox = driver.findElement(By.id("terms"));
String checked = checkbox.getAttribute("checked");
System.out.println("Checked Attribute: " + checked);
For current selection state, Selenium's isSelected() method is generally more appropriate than inspecting the checked markup attribute.
boolean selected = checkbox.isSelected();
System.out.println("Selected: " + selected);
22. getAttribute() for Disabled Attribute
The disabled attribute can be inspected using getAttribute().
WebElement button = driver.findElement(By.id("submit"));
String disabled = button.getAttribute("disabled");
System.out.println("Disabled Attribute: " + disabled);
For determining the current enabled or disabled state, isEnabled() is generally more suitable.
boolean enabled = button.isEnabled();
System.out.println("Enabled: " + enabled);
23. getAttribute() for Readonly Attribute
The readonly attribute can be retrieved from an input field.
WebElement field = driver.findElement(By.id("email"));
String readonly = field.getAttribute("readonly");
System.out.println("Readonly: " + readonly);
24. getAttribute() for Multiple Attributes
Multiple attributes can be retrieved from the same WebElement.
WebElement element = driver.findElement(By.id("username"));
String id = element.getAttribute("id");
String name = element.getAttribute("name");
String className = element.getAttribute("class");
String placeholder = element.getAttribute("placeholder");
String value = element.getAttribute("value");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Class: " + className);
System.out.println("Placeholder: " + placeholder);
System.out.println("Value: " + value);
25. getAttribute() vs getText()
A common Selenium interview question is the difference between getAttribute() and getText().
| Feature | getAttribute() | getText() |
| Purpose | Retrieves an attribute-related value | Retrieves visible text |
| Typical Use | value, href, class, id, placeholder | Heading, label, message, link text |
| Return Type | String | String |
| Example | element.getAttribute("value") | element.getText() |
| Input Value | Commonly used for input value retrieval | Generally not used for input value |
Example:
<input id="username" value="admin">
String value = element.getAttribute("value");
26. getAttribute() vs getDomProperty()
Selenium also provides DOM property methods. An HTML attribute and a DOM property are related concepts, but they are not always identical.
| Method | Purpose | Example |
| getAttribute() | Retrieve an attribute-related value | getAttribute("href") |
| getDomProperty() | Retrieve a DOM property | getDomProperty("value") |
| getText() | Retrieve visible text | getText() |
For example, the current DOM property of an input can be read using:
String value = element.getDomProperty("value");
27. getAttribute() vs getDomAttribute()
Modern Selenium versions also provide getDomAttribute(). It is useful when the requirement is specifically to retrieve the DOM attribute value.
String attribute = element.getAttribute("value");
String domAttribute = element.getDomAttribute("value");
String domProperty = element.getDomProperty("value");
Use the method that matches the test requirement: use getText() for visible text, getDomAttribute() when the DOM attribute itself is required, and getDomProperty() when the DOM property is required.
28. getAttribute() for Links
Links are a common real-world use case for getAttribute().
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String text = link.getText();
String href = link.getAttribute("href");
System.out.println("Text: " + text);
System.out.println("URL: " + href);
}
29. getAttribute() for Images
Testers can retrieve image source and alternative text attributes.
WebElement image = driver.findElement(By.id("productImage"));
String src = image.getAttribute("src");
String alt = image.getAttribute("alt");
System.out.println("Source: " + src);
System.out.println("Alt Text: " + alt);
30. getAttribute() for Product Information
In e-commerce applications, custom attributes can store product identifiers.
WebElement product = driver.findElement(By.cssSelector(".product"));
String productId = product.getAttribute("data-product-id");
String productName = product.getText();
System.out.println("Product ID: " + productId);
System.out.println("Product Name: " + productName);
31. getAttribute() for Dynamic Web Elements
Dynamic web applications may update attributes after user actions or server responses. Selenium can retrieve the current value of the requested attribute after the element reaches the expected state.
driver.findElement(By.id("search")).sendKeys("Laptop");
WebElement result = driver.findElement(By.id("result"));
String productId = result.getAttribute("data-id");
System.out.println("Product ID: " + productId);
32. getAttribute() with Explicit Wait
If an element or its required attribute is populated dynamically, an explicit wait can be used before retrieving the value.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("username"))
);
String value = element.getAttribute("value");
System.out.println(value);
Explicit waits are useful when the element is loaded asynchronously or its state changes after a user action.
33. getAttribute() for Dynamic href
Some applications generate links dynamically. The href can be retrieved after the link becomes available.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement link = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".dynamic-link"))
);
String href = link.getAttribute("href");
System.out.println("Generated URL: " + href);
34. getAttribute() for CSS Class Validation
CSS classes may change when an element enters a particular state. getAttribute() can be used to inspect the class attribute.
WebElement field = driver.findElement(By.id("email"));
String className = field.getAttribute("class");
System.out.println("Current Class: " + className);
For example, an application may add an error-related CSS class after validation fails.
35. getAttribute() for Validation State
HTML validation-related attributes can sometimes be inspected using getAttribute().
WebElement email = driver.findElement(By.id("email"));
String required = email.getAttribute("required");
String pattern = email.getAttribute("pattern");
System.out.println("Required: " + required);
System.out.println("Pattern: " + pattern);
36. getAttribute() for Placeholder Validation
Placeholder text can be validated during UI testing.
WebElement search = driver.findElement(By.id("search"));
String actualPlaceholder = search.getAttribute("placeholder");
Assert.assertEquals(actualPlaceholder, "Search Products");
37. getAttribute() for URL Verification
When a test needs to verify the destination of a link, getAttribute("href") can be used.
WebElement link = driver.findElement(By.id("privacy"));
String href = link.getAttribute("href");
Assert.assertTrue(href.contains("privacy"));
38. getAttribute() for Form Validation
getAttribute() can help inspect HTML attributes associated with form controls.
WebElement email = driver.findElement(By.id("email"));
String type = email.getAttribute("type");
String name = email.getAttribute("name");
String placeholder = email.getAttribute("placeholder");
System.out.println("Type: " + type);
System.out.println("Name: " + name);
System.out.println("Placeholder: " + placeholder);
39. getAttribute() with contains()
Retrieved attribute values can be checked using Java String methods.
String className = driver.findElement(By.id("message")).getAttribute("class");
if (className != null && className.contains("success")) {
System.out.println("Success class is present");
}
40. getAttribute() with equals()
The equals() method can be used when the complete attribute value must match.
String value = driver.findElement(By.id("username")).getAttribute("value");
if ("admin".equals(value)) {
System.out.println("Username is correct");
}
41. getAttribute() with equalsIgnoreCase()
If case-insensitive comparison is appropriate for the test requirement, equalsIgnoreCase() can be used.
String placeholder = driver.findElement(By.id("search")).getAttribute("placeholder");
if (placeholder != null && placeholder.equalsIgnoreCase("search products")) {
System.out.println("Placeholder matched");
}
42. getAttribute() for Multiple Elements
getAttribute() can be used with a collection of WebElements.
List<WebElement> links = driver.findElements(By.cssSelector("a"));
for (WebElement link : links) {
String href = link.getAttribute("href");
System.out.println(href);
}
43. getAttribute() for Multiple Input Fields
List<WebElement> inputs = driver.findElements(By.tagName("input"));
for (WebElement input : inputs) {
String name = input.getAttribute("name");
String type = input.getAttribute("type");
String value = input.getAttribute("value");
System.out.println("Name: " + name);
System.out.println("Type: " + type);
System.out.println("Value: " + value);
}
44. getAttribute() for Web Tables
Attributes of table cells or rows can be inspected when applications store additional information in HTML attributes.
WebElement row = driver.findElement(By.cssSelector("#userTable tbody tr"));
String userId = row.getAttribute("data-user-id");
System.out.println("User ID: " + userId);
45. getAttribute() for Dropdown
Dropdown option elements may contain values that are different from their visible text.
Select country = new Select(driver.findElement(By.id("country")));
for (WebElement option : country.getOptions()) {
String value = option.getAttribute("value");
String text = option.getText();
System.out.println("Value: " + value);
System.out.println("Text: " + text);
}
46. getAttribute() for Selected Option
For a standard HTML select element, the selected option can be inspected using Selenium's Select class.
Select country = new Select(driver.findElement(By.id("country")));
WebElement selectedOption = country.getFirstSelectedOption();
String value = selectedOption.getAttribute("value");
String text = selectedOption.getText();
System.out.println("Selected Value: " + value);
System.out.println("Selected Text: " + text);
47. Common Mistake: Using getText() Instead of getAttribute()
A common mistake is using getText() to retrieve an input field's current value.
Incorrect approach:
String username = driver.findElement(By.id("username")).getText();
Recommended approach:
String username = driver.findElement(By.id("username")).getAttribute("value");
48. Common Mistake: Using Wrong Attribute Name
The attribute name must match the attribute that needs to be retrieved.
For example:
String value = element.getAttribute("value");
String placeholder = element.getAttribute("placeholder");
String href = element.getAttribute("href");
Using an unrelated attribute name may return null or an unexpected result depending on the element and DOM.
49. Common Mistake: Incorrect Locator
If Selenium locates the wrong element, getAttribute() will retrieve an attribute from the wrong WebElement.
WebElement element = driver.findElement(By.id("username"));
String value = element.getAttribute("value");
Always inspect the DOM and verify that the locator identifies the intended element.
50. Common Mistake: Ignoring Dynamic Attributes
Modern web applications can dynamically modify attributes such as class, value, href, aria attributes, and data attributes.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement"))
);
String className = element.getAttribute("class");
51. Common Mistake: Not Synchronizing with the Application
If the required attribute is populated after an AJAX request or JavaScript operation, retrieving it immediately may produce an unexpected result.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(By.id("dynamicField"))
);
String value = element.getAttribute("value");
52. getAttribute() in Page Object Model
In the Page Object Model, attribute retrieval methods can be placed inside page classes to keep test classes clean and reusable.
public class LoginPage {
private WebDriver driver;
private By username = By.id("username");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public String getUsernameValue() {
return driver.findElement(username).getAttribute("value");
}
}
Test class:
String value = loginPage.getUsernameValue();
Assert.assertEquals(value, "admin");
53. getAttribute() in TestNG Automation
@Test
public void verifyPlaceholder() {
String actualPlaceholder =
driver.findElement(By.id("username")).getAttribute("placeholder");
Assert.assertEquals(actualPlaceholder, "Enter Username");
}
54. getAttribute() for E-Commerce Testing
In an e-commerce application, getAttribute() can be used to retrieve product IDs, image URLs, links, prices stored in attributes, and other metadata.
WebElement product = driver.findElement(By.cssSelector(".product"));
String productId = product.getAttribute("data-product-id");
String image = product.findElement(By.cssSelector("img")).getAttribute("src");
System.out.println("Product ID: " + productId);
System.out.println("Image URL: " + image);
55. getAttribute() for Cart Validation
WebElement cart = driver.findElement(By.id("cart"));
String itemCount = cart.getAttribute("data-item-count");
System.out.println("Cart Items: " + itemCount);
Assert.assertEquals(itemCount, "2");
56. getAttribute() for Login Validation
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("Admin@123");
WebElement username = driver.findElement(By.id("username"));
String enteredUsername = username.getAttribute("value");
Assert.assertEquals(enteredUsername, "admin");
57. getAttribute() for Image Validation
WebElement image = driver.findElement(By.cssSelector(".product-image"));
String src = image.getAttribute("src");
String alt = image.getAttribute("alt");
Assert.assertTrue(src.contains("product"));
Assert.assertEquals(alt, "Laptop Computer");
58. getAttribute() for Navigation Links
List<WebElement> navigationLinks =
driver.findElements(By.cssSelector(".navigation a"));
for (WebElement link : navigationLinks) {
String text = link.getText();
String href = link.getAttribute("href");
System.out.println("Link Text: " + text);
System.out.println("Link URL: " + href);
}
59. Real-Time Example: Login Form Attribute Verification
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class LoginAttributeTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com/login");
WebElement username = driver.findElement(By.id("username"));
String type = username.getAttribute("type");
String name = username.getAttribute("name");
String placeholder = username.getAttribute("placeholder");
Assert.assertEquals(type, "text");
Assert.assertEquals(name, "username");
Assert.assertEquals(placeholder, "Enter Username");
driver.quit();
}
}
60. Real-Time Example: Verify Entered Username
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
String actualValue = username.getAttribute("value");
Assert.assertEquals(actualValue, "admin");
System.out.println("Username verified successfully");
61. Real-Time Example: Verify Link URL
WebElement contactLink = driver.findElement(By.linkText("Contact Us"));
String actualUrl = contactLink.getAttribute("href");
System.out.println("Contact URL: " + actualUrl);
Assert.assertTrue(actualUrl.contains("contact"));
62. Real-Time Example: Verify Product Attributes
WebElement product = driver.findElement(By.cssSelector(".product"));
String productId = product.getAttribute("data-product-id");
String productClass = product.getAttribute("class");
System.out.println("Product ID: " + productId);
System.out.println("Product Class: " + productClass);
Assert.assertNotNull(productId);
63. Practical Project Using getAttribute()
A practical Selenium project can use getAttribute() throughout a complete web application workflow.
Open Browser
↓
Open Login Page
↓
Locate Username Field
↓
Retrieve Placeholder
↓
Enter Username
↓
Retrieve Input Value
↓
Enter Password
↓
Click Login
↓
Open Dashboard
↓
Retrieve Navigation Link href
↓
Search Product
↓
Retrieve Product ID
↓
Retrieve Product Image src
↓
Add Product to Cart
↓
Retrieve Cart Item Count
↓
Verify Attributes
Example validation points:
- Verify username field placeholder.
- Verify entered username value.
- Verify password field type.
- Verify navigation link href.
- Verify product data attributes.
- Verify image src and alt attributes.
- Verify cart item count.
64. Best Practices for getAttribute()
- Use getAttribute() when the required information is stored in or associated with an HTML attribute.
- Use getText() for visible text.
- Use getAttribute("value") for appropriate input value retrieval.
- Use getAttribute("href") to inspect link destinations.
- Use getAttribute("src") to inspect image or resource URLs.
- Use meaningful variable names such as actualValue, href, placeholder, or productId.
- Use explicit waits when elements or their attributes are populated dynamically.
- Use TestNG assertions to validate expected attribute values.
- Keep reusable attribute retrieval methods inside Page Object classes.
- Inspect the DOM when an attribute value is not returned as expected.
- Use getDomAttribute() when the test specifically requires the DOM attribute.
- Use getDomProperty() when the test specifically requires the DOM property.
- Avoid unnecessary Thread.sleep() calls when proper synchronization can be used.
65. Advantages of getAttribute()
| Advantage | Description |
| Simple | Easy to use for retrieving attribute-related values. |
| Useful for Validation | Helps verify href, value, class, placeholder, id, and other attributes. |
| Useful for Input Fields | Can be used for retrieving input values when appropriate. |
| Useful for Links | Can retrieve href values for navigation validation. |
| Useful for Images | Can retrieve src and alt attributes. |
| Supports Automation | Can be combined with assertions and automation frameworks. |
| Useful for Dynamic Applications | Can inspect dynamically generated attribute-related values. |
66. Limitations of getAttribute()
- It is not the primary method for retrieving visible text.
- It may not be the appropriate method when the requirement specifically concerns a DOM property.
- Dynamic attributes may require synchronization.
- Incorrect attribute names can produce null or unexpected results.
- Incorrect locators can result in retrieving values from the wrong element.
- Attribute values can differ from information visually displayed to the user.
- For strict DOM attribute semantics, getDomAttribute() may be more appropriate.
- For strict DOM property semantics, getDomProperty() may be more appropriate.
67. getAttribute() Quick Reference
| Requirement | Recommended Approach |
| Retrieve input value | getAttribute("value") |
| Retrieve link URL | getAttribute("href") |
| Retrieve image URL | getAttribute("src") |
| Retrieve CSS class | getAttribute("class") |
| Retrieve element ID | getAttribute("id") |
| Retrieve name | getAttribute("name") |
| Retrieve placeholder | getAttribute("placeholder") |
| Retrieve title | getAttribute("title") |
| Retrieve custom data attribute | getAttribute("data-product-id") |
| Retrieve visible text | getText() |
| Retrieve DOM attribute specifically | getDomAttribute() |
| Retrieve DOM property specifically | getDomProperty() |
| Check current checkbox selection | isSelected() |
| Check current enabled state | isEnabled() |
68. getAttribute() Interview Questions
Q1. What is getAttribute() in Selenium?
getAttribute() is a WebElement method used to retrieve an attribute-related value from a web element.
Q2. What does getAttribute() return?
It returns the requested value as a String when a value is available.
Q3. How do you retrieve the value entered in an input field?
The input value can commonly be retrieved using getAttribute("value").
Q4. How do you retrieve the URL of a link?
Use getAttribute("href") on the link WebElement.
Q5. What is the difference between getText() and getAttribute()?
getText() is used to retrieve visible text, while getAttribute() is used to retrieve an attribute-related value.
Q6. Can getAttribute() retrieve the class of an element?
Yes. Use getAttribute("class").
Q7. Can getAttribute() retrieve placeholder text?
Yes. Use getAttribute("placeholder").
Q8. Can getAttribute() be used with XPath?
Yes. XPath can locate the WebElement, and getAttribute() can retrieve the required attribute-related value.
Q9. Can getAttribute() be used with CSS selectors?
Yes. CSS selectors can locate the WebElement before getAttribute() is called.
Q10. What should be used for visible text?
getText() is generally used when the requirement is to retrieve visible text.
Q11. What is getDomAttribute()?
getDomAttribute() is used when the requirement is specifically to retrieve a DOM attribute value.
Q12. What is getDomProperty()?
getDomProperty() is used when the requirement is to retrieve a DOM property.
Q13. What should be used to check whether a checkbox is currently selected?
The isSelected() method is generally used to determine the current selection state of a checkbox or radio button.
Q14. What should be used to check whether an element is currently enabled?
The isEnabled() method is used to determine the current enabled state of an element.
69. getAttribute() Best Practices Checklist
- Identify the correct WebElement before calling getAttribute().
- Specify the exact attribute name that needs to be retrieved.
- Use getText() when the requirement is visible text.
- Use getAttribute("value") for appropriate input value retrieval.
- Use getAttribute("href") for link URL validation.
- Use getAttribute("src") for image source validation.
- Use getAttribute("placeholder") for placeholder validation.
- Use explicit waits for dynamically populated elements.
- Use assertions for automated attribute validation.
- Use meaningful variable names.
- Keep reusable attribute retrieval logic inside Page Object classes.
- Use getDomAttribute() when exact DOM attribute semantics are required.
- Use getDomProperty() when DOM property semantics are required.
- Use isSelected() for current checkbox or radio-button selection state.
- Use isEnabled() for current enabled or disabled state.
70. Conclusion
The getAttribute() method is an important Selenium WebDriver method for retrieving attribute-related values from web elements. It is widely used for verifying input values, href URLs, image sources, CSS classes, IDs, names, placeholders, titles, custom data attributes, and other HTML-related information.
Understanding the difference between getAttribute(), getText(), getDomAttribute(), and getDomProperty() helps testers choose the appropriate Selenium API for different validation requirements. When combined with locators, explicit waits, TestNG assertions, and Page Object Model, getAttribute() becomes useful for building maintainable Selenium automation tests.
To learn Selenium WebDriver, Java automation, TestNG, locators, automation frameworks, and practical testing projects, visit the JustAcademy Selenium Training Course. For a course demonstration, use the JustAcademy Course Demo Registration.