Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
dom
communitycreator

What is the getAttribute() method in DOM?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

html
dom
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring