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 to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources