The Element.getAttribute()
method is used to get the attribute value of an element.
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.
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.