How to get the value of an attribute using JavaScript

published: 25 Sep 2022

2 min read

How to get the value of an attribute using 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:

<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:

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:

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:

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.

How to get the value of an attribute using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming