In this shot, we will learn how to find if the DOM element has the specified attribute or not.
We will use the DOM hasAttribute()
method, which takes one parameter, which is an attribute name of type string.
This method will return a boolean value. It will be true
if the element upon which we apply the method has the attribute, and false
if it does not have any attribute you specified in the parameter.
Let’s try to find if the button element has the onclick
attribute or not.
In line 5
, we have a paragraph tag for displaying text.
In line 7
, we write a button tag with an id=elem
and function change()
. It will be called when the user clicks on it.
In line 10
, in the script tag, we write the JavaScript code. We define a function change()
, in which the click will call on the button from HTML
page.
In line 11
, we select the <button>
element using document.getElementById()
and store it in a variable.
In line 12
, we apply the method hasAttribute()
on the variable which has the button
element. Inside the method, we will pass the attribute name and store it in a variable.
In line 13, we print the returned value from the method hasAttribute()
by console.log()
.
When we click the button, we get the boolean value on the console. It is true
, which means the button element with id elem
has an attribute that we passed as a parameter.