JavaScript – Get Attributes of HTML Element Element
To get attributes of an HTML Element using JavaScript, get reference to this HTML Element using a selector, and read the attributes
property of this HTML Element.
In the following example, we have HTML Element with id "myElement"
, and we shall get the attributes of this HTML Element in JavaScript by reading this element’s attributes
property.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#myElement {
border:1px solid #CCC;
width:100px;
height:100px;
}
</style>
<meta charset="utf-8">
</head>
<body>
<h2>Get Attributes of HTML Element in JavaScript</h2>
<div id="myElement" class="dummy" style="width:100px;height:100px;background:#CCC;">Hello World!</div>
<br>
<button type="button" onclick="printAttributes()">Click Me</button>
<script>
function printAttributes(){
var element = document.getElementById("myElement");
var attribs = element.attributes;
console.log(attribs);
}
</script>
</body>
</html>
Try this program online, and open Developer Tools. Open Console window.
Click on the 'Click Me'
button in our HTML page. The following shall be displayed in the console window.
attributes
property returns NameNodeMap object with the attributes in the HTML Element, where the attributes can be accessed using name of the attribute or the index.
Let us print the class attribute to console.
Example – Print Attributes in For Loop
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#myElement {
border:1px solid #CCC;
width:100px;
height:100px;
}
</style>
<meta charset="utf-8">
</head>
<body>
<h2>Get Attributes of HTML Element in JavaScript</h2>
<div id="myElement" class="dummy" style="width:100px;height:100px;background:#CCC;">Hello World!</div>
<br>
<button type="button" onclick="printAttributes()">Click Me</button>
<script>
function printAttributes(){
var element = document.getElementById("myElement");
var attribs = element.attributes;
for(var i = 0; i < attribs.length; i++) {
console.log(attribs[i]);
}
}
</script>
</body>
</html>
Try online, open Console window in Developer tools, and click on the Click Me
button in the HTML page.
Conclusion
In this JavaScript Tutorial, we learned how to get the attributes of an HTML element using JavaScript.