The following code shows an example of the getAttribute() method in JavaScript.
Programmingempire
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.
<html>
<head>
<title>Attribute Values</title>
<script>
function f1()
{
var v1=document.getElementById("g1");
var v2=document.getElementById("d3");
str="";
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");
str1=v2.innerHTML;
str1+="<br/>"+str;
v2.innerHTML=str1;
}
</script>
<style>
.c1{
border: 10px solid #ffff22;
border-radius: 600px;
}
</style>
</head>
<body>
<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>
</div>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
Understanding HTTP Requests and Responses
What is Asynchronous JavaScript?
JavaScript Code for Event Handling
Callback Functions in JavaScript
Show or Hide TextBox when Selection Changed in JavaScript
Changing Style of HTML Elements using getElementsByClassName() Method