sodcalculator

10 Tech How-To

Get HTML Attribute Values with Selenium & JavaScript

Guide 10-59427 · Updated · Step by step

This guide shows you how to retrieve the value of any HTML attribute (like href, class, or data-*) from a web element using Selenium WebDriver and JavaScript. You’ll learn the exact code for both Java and Python, how to handle dynamic elements, and what to do when the attribute doesn’t exist. No prior JavaScript knowledge is needed—just basic Selenium setup.

What You’ll Need

  • A working Selenium WebDriver setup (Java or Python) with a browser driver (e.g., ChromeDriver) installed.
  • Basic familiarity with locating elements (by ID, class, XPath, etc.).
  • An IDE or text editor to write and run your test scripts.

Step-by-Step

  1. Locate the element. Use any standard Selenium locator to find the element whose attribute you need. For example, in Java: WebElement element = driver.findElement(By.id("myButton")); In Python: element = driver.find_element(By.ID, "myButton").
  2. Use the built-in getAttribute() method. The simplest way is to call element.getAttribute("attributeName") in Java or element.get_attribute("attributeName") in Python. This returns the attribute’s value as a string, or null/None if it doesn’t exist.
  3. Execute JavaScript for more complex cases. If you need to get an attribute that is dynamically set after page load, or if you prefer a JavaScript approach, use JavascriptExecutor. In Java: String value = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].getAttribute('attributeName');", element); In Python: value = driver.execute_script("return arguments[0].getAttribute('attributeName');", element).
  4. Handle missing attributes. Always check if the returned value is null/None before using it. For example, in Java: if (value != null) { ... } In Python: if value is not None: ....
  5. Retrieve multiple attributes. You can call the method multiple times on the same element to get different attributes. For efficiency, you can also pass a JavaScript function that returns an object with all needed attributes at once.
  6. Work with dynamic attributes. If the attribute changes after an action (e.g., after a click), re-locate the element or use explicit waits to ensure the new value is present before retrieving it.
  7. Use for validation. Common use cases: verify a link’s href, check a CSS class for state changes, or read data-* attributes for test data.

Common Mistakes

  • Using getAttribute() on a non-existent attribute—it returns null, not an empty string. Handle it explicitly.
  • Forgetting that getAttribute() returns the property value, not the attribute value. For example, getAttribute("value") on an input reflects the current value, not the initial HTML attribute.
  • Using JavaScript without casting the result—in Java, executeScript returns an Object, so cast to String (or other type) to avoid class cast exceptions.
  • Not waiting for the element to be present. If the element is not yet in the DOM, you’ll get a NoSuchElementException. Use explicit waits.
  • Assuming attribute names are case-sensitive. HTML attributes are case-insensitive, but JavaScript property names are case-sensitive. Use the exact casing from the HTML.

Tips

  • Use getAttribute("class") to check for CSS class changes, which is a common way to verify UI state.
  • For boolean attributes like disabled, getAttribute() returns "true" or null—not a boolean. Convert to boolean with Boolean.parseBoolean() in Java or value is not None in Python.
  • When using JavaScript, you can also use arguments[0].getAttributeNames() to list all attributes, but this is not supported in older browsers.
  • If you need the attribute value for logging, avoid printing sensitive data (like passwords) to the console.
  • Prefer the built-in getAttribute() over JavaScript unless you have a specific reason—it’s simpler and less error-prone.

Troubleshooting

  • Getting null for an attribute that should exist. Check if the element is inside an iframe or shadow DOM—you need to switch context first. Also verify the attribute name spelling and case.
  • JavaScript returns undefined. This means the attribute doesn’t exist. In JavaScript, element.getAttribute("foo") returns null if missing, but element.foo returns undefined. Use getAttribute() inside the script.
  • StaleElementReferenceException. The element is no longer attached to the DOM. Re-find the element before retrieving the attribute.
  • Attribute value is empty string. This is valid—the attribute exists but has no value (e.g., class=""). Don’t confuse it with missing.
  • Browser driver not supporting JavaScript execution. Ensure you’re using a modern driver and that JavaScript is enabled in the browser.

Frequently Asked Questions

Can I get an attribute without locating the element first?

No, you must locate the element first. You can use JavaScript to find the element directly, but it’s cleaner to use Selenium’s locators.

What’s the difference between getAttribute() and getProperty()?

getAttribute() returns the HTML attribute value as set in the markup, while getProperty() returns the current JavaScript property value. For example, an input’s value attribute is the default, but the property reflects what the user typed.

How do I get all attributes of an element?

Use JavaScript: return arguments[0].attributes; and iterate over the namedNodeMap. This returns a list of attribute nodes.

Why does getAttribute("href") return a full URL instead of the exact HTML value?

For href and src attributes, the browser normalizes relative URLs to absolute ones. To get the raw value, use JavaScript: return arguments[0].getAttribute("href")—but note that even this may return the absolute URL in some browsers. Use getAttribute("href") in Selenium to get the absolute URL; if you need the exact string, inspect the HTML source.

Is it possible to get an attribute value in a headless browser?

Yes, headless browsers work the same way. Just make sure your driver is configured for headless mode.

Can I use this technique to get attribute values from elements inside a shadow DOM?

Yes, but you need to traverse the shadow root first. Use JavaScript to access the shadow root and then find the element.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →