What is the getAttribute() method in DOM?

Overview

In this shot, we will learn how to get the attribute value of any element using the DOM method getAttribute().

getAttribute() takes one parameter, which is the name of attribute like class, id, src, etc. This method will return the attribute value assigned in the HTML.

Example

Let’s try to get the attribute value of a div element using the getAttribute() method.

Console
Example of the getAttribute() method

Explanation

  • In line 5, CSS for the elements with class name elem is given. It sets the color property to green.

  • In line 12, the div element with class elem is defined, and text is written inside it.

  • In line 14, we have a paragraph tag to display text.

  • In line 16, we wrote a button tag which has a function named change(). It will be called when the user clicks on it.

  • In line 19, in the script tag, we have written JavaScript code. We defined a function change(), which will be called by the click on the button from the HTML page.

  • In line 20, we will get the div element object using getElementByTagName(). The returned value will a list of div elements, so we will use index=0 to get the first div.

  • In line 21, we will apply the method getAttribute('class') on the div element we received in the previous line, 20. It will return the value which it holds.

  • In line 22, we will print the value we got from the element attributes (last step) and print it on the console.

Output

When we click the click here button, the result we get is elem, which is correct. We assigned the class name in the div element as elem, and when we use getAttribute() method, it returns the value we assigned in the HTML.

Free Resources