In this tutorial we will learn How To Check if Attribute Exists or not using JavaScript. We can use hasAttribute() method for this purpose which can check if the selected HTML element has the specified attribute or not.
Table of Contents
hasAttribute() method
hasAttribute() method returns true if it finds the defined attribute in the HTML element and false if the attribute is not found.
In this example we have used hasAttribute() method to check if the attribute exists or not.
HTML Code
HTML Code is given below, in this code we have a main div tag with class attribute, a button tag with onclick event is also used.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Check if Attribute Exists or not</title>
<style>
.classDiv
{
background-color: red;
margin: 20px 0px;
padding: 10px;
}
</style>
</head>
<body>
<div id='mainDiv' class="classDiv">
I have a class Attribute, you can confirm by clicking the button.
</div>
<button onclick="checkAttribute()">Check Attribute</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function checkAttribute() will check if the class attribute exists or not on click of a button.
getElementById() method is used to select the div tag.
It's attribute is then checked using hasAttribute() method.
You can check any attribute with hasAttribute() method.
Attribute to be checked is defined inside the hasAttribute() method.
Check the following code.
<script>
function checkAttribute()
{
var element = document.getElementById('mainDiv');
if (element.hasAttribute("class"))
{
alert("Attribute exists!");
}
else
{
alert("Attribute doesn't exist!");
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on How To Check if Attribute Exists or not with JavaScript.