EN
JavaScript - hasAttribute() method example
0
points
In this article, we would like to check if the element has attributeĀ using hasAttribute()
Ā methodĀ in JavaScript.
Quick solution:
element.hasAttribute(attributeName);
Where:
element
-Ā the element we want to check if it has a given attribute,attributeName
-Ā name of the attribute we want to check if exists.
Ā
Practical example
In this example, we will check ifĀ myDiv
Ā element hasĀ class
Ā andĀ onclick
Ā attributes usingĀ hasAttribute()
Ā method.
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<head>
<style>
.blue {
background: lightblue;
}
</style>
</head>
<body>
<div id="my-div" class="blue">This is my div.</div>
<script>
var myDiv = document.querySelector('#my-div'); // get element by id
var classCheck = myDiv.hasAttribute('class'); // check if myDiv has class attribute
var onclickCheck = myDiv.hasAttribute('onclick'); // check if myDiv has onclick attribute
console.log(classCheck); // true
console.log(onclickCheck); // false
</script>
</body>
</html>