Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To read one attribute from an element in browser JavaScript, select the element and call getAttribute(): document.querySelector('a')?.getAttribute('href'). The result is the attribute’s string value, or null if the element exists but does not have that attribute. In Playwright, use locator.getAttribute(); in Selenium Python, use get_dom_attribute() when you specifically need the markup attribute rather than a live DOM property.

Choose the right method for the job

First decide what you mean by “attribute” and which environment has loaded the page. An HTML attribute is a value written on an element, such as href on a link or data-id on a custom element. A DOM property is a JavaScript-facing value associated with an element; it may represent current state rather than the original markup. These can differ, so the right method depends on whether you want the markup value or the element’s current state.

  • Page open in a browser: use Element.getAttribute().
  • Automated browser test with Playwright: use locator.getAttribute() to retrieve a value, or toHaveAttribute() for an assertion.
  • Automated browser test with Selenium Python: use get_dom_attribute() for the HTML attribute, and get_property() when the property is what you need.

In all three cases, locate the intended element first. A selector that matches a different element, or several elements when you intended one, is a selection problem rather than an attribute-reading problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read an attribute in browser JavaScript

Read one element

Open the page whose DOM you want to inspect, then run this in the browser’s developer console or in code that runs on that page:

#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
const link = document.querySelector('a');
const href = link?.getAttribute('href');

if (href !== null && href !== undefined) {
  console.log(href);
}

querySelector('a') selects the first matching anchor. The optional chain handles the case where there is no matching element: then href is undefined. If an element was found but it has no href attribute, getAttribute('href') returns null. The check handles both cases before you use the value as a string.

Replace a with a selector for the target element and href with the attribute name you want. For example, document.querySelector('img')?.getAttribute('src') reads the first matching image’s src, while document.querySelector('[aria-label]')?.getAttribute('aria-label') reads an accessible label.

Read attributes from every matching element

querySelectorAll() returns all elements matched by a selector. Convert that collection to an array and map each element to the requested attribute:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const values = [...document.querySelectorAll('[data-id]')]
  .map(element => element.getAttribute('data-id'));

console.log(values);

This selector matches elements that have a data-id attribute; the call retrieves the value from each match. Use a more specific selector if the page has unrelated elements with the same attribute. If you need several attributes from each match, map to an object:

const items = [...document.querySelectorAll('a')].map(link => ({
  href: link.getAttribute('href'),
  label: link.getAttribute('aria-label'),
  className: link.getAttribute('class')
}));

The selector decides what enters the result. It does not guarantee that every returned attribute has a value: a missing attribute produces null.

Attribute names and parsed values

For an HTML element in an HTML document, the name supplied to getAttribute() is normalized to lowercase. HTML character references are decoded when the document is parsed, so the returned value is the DOM’s parsed attribute value rather than a raw slice of the original response text. See MDN’s Element: getAttribute() method reference for the method’s return behavior and details.

Attribute versus property: choose the value you actually need

getAttribute('name') reads the content attribute. A property can instead reflect the element’s current state. For example, an input’s current value may change while the markup’s value attribute remains the content attribute. If the task concerns the control’s live state, read its relevant property; do not assume the attribute is current.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This distinction is especially important in Selenium. Its Python get_attribute() convenience method checks the property first and falls back to the attribute, and it can coerce certain boolean-like values. Use get_dom_attribute() when you mean the markup attribute, or get_property() when you mean the DOM property. Selenium documents this behavior in its Python WebElement API.

Do not substitute innerHTML, outerHTML, .text or textContent when the task is to retrieve one attribute. Those expose markup or text content, not the requested attribute value. If a dynamic-page result differs from visible text, check that you are reading the intended element and the intended kind of value.

Read an attribute with Playwright

Assuming page is an already configured Playwright page, use a locator and call getAttribute():

const href = await page.locator('a').getAttribute('href');
console.log(href);

The locator identifies the target and the method reads its attribute. Use a selector specific enough to target the intended link. The Playwright Locator API documents getAttribute().

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a retry-aware assertion in tests

If your goal is to verify an attribute in a test, prefer Playwright’s recommended assertion rather than reading once and comparing the returned value yourself:

await expect(page.locator('a')).toHaveAttribute('href', expectedHref);

This expresses the intended assertion directly and avoids a one-time read-and-compare pattern that can be flaky when the page is changing. The locator must still identify the element you mean.

Read an attribute with Selenium Python

In Selenium, first find the element and then read its DOM attribute. The example assumes driver is an active WebDriver session and the required Selenium imports are already in place:

from selenium.webdriver.common.by import By

link = driver.find_element(By.CSS_SELECTOR, "a")
href = link.get_dom_attribute("href")

if href is not None:
    print(href)

Use a selector more specific than a when the page has multiple links and only one is relevant. get_dom_attribute() returns None if the element does not have the requested attribute. Selenium’s Finding web elements guide demonstrates the find-then-read workflow; the Python WebElement API explains the distinction between DOM attributes and properties.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Handle missing elements and attributes safely

There are two different failure cases, and they call for different fixes:

  • The element was not found: a browser JavaScript query such as querySelector() returns null; in Selenium, find_element() reports a locator failure. Check the selector, the page state and whether the element is present before querying it.
  • The element exists but lacks the attribute: browser JavaScript returns null; Selenium Python’s DOM-attribute method returns None. Check for that absence before calling string methods such as .trim() or concatenating the value.

When several elements match, decide whether you want the first match or every match. In browser JavaScript, querySelector() selects the first; querySelectorAll() gives you the matching collection to iterate over. In Playwright and Selenium, make the locator specific to the intended element rather than silently relying on an ambiguous match.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common mistakes

The result is null or None

That means the selected element does not have the requested attribute. Confirm the element is the right one, check the spelling of the attribute name and handle absence explicitly. Do not treat a missing attribute as an empty string unless that is a deliberate choice in your application.

The element lookup fails

This is not the same as a missing attribute: the automation could not locate the element at all. Recheck the selector and whether the target exists in the document at the time of the query. In browser JavaScript, guard the result of querySelector() before calling a method on it. In Selenium, follow the find-then-read workflow and address the locator failure before attempting extraction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The value differs from what the page currently shows

Check whether you need the content attribute or a live property. The markup attribute can represent the original content, while a property such as an input’s current value can represent changed state. In Selenium, avoid get_attribute() when you specifically need the markup attribute; choose get_dom_attribute() or get_property() according to the value you are trying to read.

You used a text or HTML method

.text, textContent, innerHTML and outerHTML answer different questions. Use the attribute API for a value such as href, src, class, id, aria-label or data-*.

You are trying to extract from a page that has not been loaded into a DOM

These examples read elements in a document already available to the browser or automation session. They are not a way to fetch arbitrary HTML without loading or parsing it. Establish the page in the appropriate environment, identify the target element, then read its attribute.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a DOM-attribute reader. It cannot return an element’s href or data-* value; use the JavaScript, Playwright or Selenium method above for that. If you also need a visual screenshot of the page, one GET request can capture it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Before capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers indicate the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info and capture_pdf tools for AI agents using Claude, Cursor or another MCP client. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.