JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get the attribute value of an element in JavaScript?

With the help of getAttribute() method, you can get the value of an attribute. The format of the getAttribute() method is

let attributeValue = htmlElement.getAttribute(attributeName);

For example, if you want to get the value of the src attribute of an img element, call the getAttribute() method and pass the src attribute to it.

HTML Code

<img src="/images/javascript.png" id="logo" />

JavaScript Code

let image = document.getElementById('logo');
let imageSource = image.getAttribute('src');

The best thing about the getAttribute() method is that you can get the value of data-* attribute using this method.

For example, to get the value of the data-color attribute of an img element, you have to select the img element and then call the getAttribute() method.

<img src="/images/javascript.png" data-color="yellow" id="logo" />
let image = document.getElementById('logo');
let imageSource = image.getAttribute('data-color');

Recommended Posts