Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Value of the class attribute node of an element in JavaScript?
JavaScript provides the getAttributeNode() method to retrieve the attribute node of an element as an attribute object. This method returns the attribute node with the specified name, or null if the attribute doesn't exist.
Syntax
element.getAttributeNode(attributename);
It returns the attribute object representing the specified attribute node. To get the actual value, use the value property of the returned object.
Example: Getting Class Attribute Value
In this example, we have two heading tags with different classes. We'll use getAttributeNode() to retrieve the class attribute and display its value.
<html>
<body>
<h2 class="class1">Tutorix</h2>
<h2 class="class2">Tutorialspoint</h2>
<p id="attribute"></p>
<script>
var elmnt = document.getElementsByTagName("h2")[1];
var classNode = elmnt.getAttributeNode("class");
var value = classNode.value;
document.getElementById("attribute").innerHTML = "Class value: " + value;
</script>
</body>
</html>
Output
Tutorix Tutorialspoint Class value: class2
Working with Multiple Classes
When an element has multiple classes, getAttributeNode("class").value returns the complete class string. You can split it to access individual classes:
<html>
<body>
<div class="primary button large">Click me</div>
<p id="result"></p>
<script>
var element = document.querySelector("div");
var classNode = element.getAttributeNode("class");
var classValue = classNode.value;
var classList = classValue.split(" ");
document.getElementById("result").innerHTML =
"Full class: " + classValue + "<br>" +
"Individual classes: " + classList.join(", ");
</script>
</body>
</html>
Output
Click me Full class: primary button large Individual classes: primary, button, large
Error Handling
Always check if the attribute node exists before accessing its value to avoid errors:
<html>
<body>
<p>Paragraph without class</p>
<p id="output"></p>
<script>
var element = document.querySelector("p");
var classNode = element.getAttributeNode("class");
if (classNode) {
document.getElementById("output").innerHTML = "Class: " + classNode.value;
} else {
document.getElementById("output").innerHTML = "No class attribute found";
}
</script>
</body>
</html>
Output
Paragraph without class No class attribute found
Alternative Methods
While getAttributeNode() works well, you can also use simpler methods like getAttribute("class") or the className property for getting class values directly.
Conclusion
The getAttributeNode() method provides access to attribute objects, including class attributes. Always check for null values and use the value property to get the actual attribute content.
