# How to get the value of an attribute using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 10, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-get-the-value-of-an-attribute

> Learn how to get the value of an HTML element's attribute by using the getAttribute() method in JavaScript.

To get the value of an attribute of an element, you can use the `getAttribute()` method. This method returns the value of the attribute with the specified name. If the attribute does not exist, it returns `null` or an empty string (`""`).

Let us say you have the following anchor element:

```javascript
<a href="http://example.com" title="Go Back" data-role="self">Click Me</a>
```

Now you want to get the value of the `href` attribute. Here is a code snippet that you can use:

```javascript
const anchor = document.querySelector('a');

const href = anchor.getAttribute('href');

console.log(href); // http://example.com
```

The `getAttribute()` method also works for the HTML5 `data-*` attributes.

For example, to get the value of the `data-role` attribute of the anchor element, you can use the `getAttribute()` method as follows:

```javascript
const anchor = document.querySelector('a');

const role = anchor.getAttribute('data-role');

console.log(role); // self
```

If you want to get the value of the attribute as an `Attr` object, use the `getAttributeNode()` method instead:

```javascript
const anchor = document.querySelector('a');

const attr = anchor.getAttributeNode('title');

console.log(attr.value); // Go Back
```

The `getAttribute()` method works in all modern browsers, and IE9 and up.
