Get the Value of an Attribute

Summary: in this tutorial, you will learn how to get the value of an attribute of an element using the getAttribute() method.

To get the value of an attribute of an element, you use the getAttribute() method:

let attributeValue = element.getAttribute(attributeName);Code language: JavaScript (javascript)

For example, to get the value of the title attribute of an anchor element, you use the following code:

const link = document.querySelector('a');
let title = link.getAttribute('title');Code language: JavaScript (javascript)

It’s possible to use the getAttribute() method to get the data-* attribute. For example:

<a href="/api" data-method="post">Save</a>Code language: HTML, XML (xml)

To get the value of the data-method attribute of the anchor element, you use the getAttribute() method as follows:

const link = document.querySelector('a');
let method = link.getAttribute('data-method');Code language: JavaScript (javascript)
Was this tutorial helpful ?