Check if Attribute Exists or not using JavaScript

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.

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.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color