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:
xxxxxxxxxx
1
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.
In this example, we will check if myDiv
element has class
and onclick
attributes using hasAttribute()
method.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.blue {
6
background: lightblue;
7
}
8
</style>
9
</head>
10
<body>
11
<div id="my-div" class="blue">This is my div.</div>
12
<script>
13
var myDiv = document.querySelector('#my-div'); // get element by id
14
var classCheck = myDiv.hasAttribute('class'); // check if myDiv has class attribute
15
var onclickCheck = myDiv.hasAttribute('onclick'); // check if myDiv has onclick attribute
16
console.log(classCheck); // true
17
console.log(onclickCheck); // false
18
</script>
19
</body>
20
</html>