The following code shows an example of the getAttribute() method in JavaScript.


Demonstrating Example of the getAttribute() Method in JavaScript

As can be seen in the following code, we use the getAttribute() method to find the value of the class, src, alt, width, and height attributes of the image. Also, these values are displayed in a div element.

  <title>Attribute Values</title>
     function f1()
	var v1=document.getElementById("g1"); 
	var v2=document.getElementById("d3"); 
        str+="<br/>CSS Class: "+v1.getAttribute("class");
        str+="<br/>Src: "+v1.getAttribute("src");
        str+="<br/>Alt: "+v1.getAttribute("alt");
        str+="<br/>Width: "+v1.getAttribute("width");
        str+="<br/>Height: "+v1.getAttribute("height");
       border: 10px solid #ffff22;
       border-radius: 600px;
  <div id="d1" style="margin: 50px; padding: 20px; text-align: center;
      font-size: 20px;background-color:#ffddaa;color:#ff3311; width: 500px;"><br/><br/>
     <img class="c1" id="g1" src="j4.jpg" alt="My Image" width="250" height="300"/><br/><br/>
     <button onclick="f1()">Get Attribute Values</button>
     <div id="d3">Attribute Values...</div>


The Output of the  Example of the getAttribute() Method in JavaScript
The Output of the Example of the getAttribute() Method in JavaScript

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

Understanding JSON Web Tokens

Understanding HTTP Requests and Responses

What is Asynchronous JavaScript?

JavaScript Code for Event Handling

Callback Functions in JavaScript

Arrow Functions in JavaScript

JavaScript Code Examples

Show or Hide TextBox when Selection Changed in JavaScript

Changing Style of HTML Elements using getElementsByClassName() Method

Creating Classes in JavaScript