What is the Element.getAttribute() method in JavaScript?

The Element.getAttribute() method is used to get the attribute value of an element.

Syntax

let attVal = element.getAttribute(attributeName);

If there is no attribute present for the given attribute name, then Element.getAtrribute() returns null or an empty string ("").

The attributeName argument is converted to lowercase internally before getting the value for the attribute.

Example

Let’s say we have a div element with the attribute rating.

<div rating="4">Educative</div>

To get the value of the rating attribute, we can use the getAttribute method.

let divEle = document.querySelector('div');
let rating = divEle.getAttribute('rating');
let name = divEle.getAttribute('name');

console.log(rating); // 4
console.log(name); // null

This will print 4 in the console.


Complete example

Console
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources