EN
JavaScript - check if element / node has attribute
0 points
In this article, we would like to show you how to check if element / node has the attribute in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#element-id'); // get element by id
2
3
myElement.hasAttribute(attributeName); // check if element has the attribute
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>