Home / Questions / How to get Attributes of Div Element in JavaScript?
Explanatory Question

How to get Attributes of Div Element in JavaScript?

👁 273 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

JavaScript – Get Attributes of Div Element

To get attributes of a div using JavaScript, get reference to the div element, and read the attributes property of the div element.

In the following example, we have div with id "myDiv", and we shall get the attributes of this div in JavaScript using attributes property.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head> 
<body>
    <h2>Get Attributes of Div using JavaScript</h2>
    <div id="myDiv" class="dummy" style="width:100px;height:100px;background:#CCC;"></div>
    <br>
    <button type="button" onclick="getAttributes()">Click Me</button>
    <script>
    function getAttributes(){
        var element = document.getElementById("myDiv");
        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.

JavaScript - Get Attributes of Div Element
Figure: JavaScript - Get Attributes of Div Element

attributes property returns NameNodeMap object with the attributes in the div 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>
<meta charset="utf-8">
</head> 
<body>
    <h2>Get Attributes of Div using JavaScript</h2>
    <div id="myDiv" class="dummy" style="width:100px;height:100px;background:#CCC;"></div>
    <br>
    <button type="button" onclick="getAttributes()">Click Me</button>
    <script>
    function getAttributes(){
        var element = document.getElementById("myDiv");
        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.

JavaScript - Print Attributes of Div Element
Figure: JavaScript - Print Attributes of Div Element