How to use the DOM hasAttribute() method
Overview
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.
Code
Let’s try to find if the button element has the onclick attribute or not.
Code explanation
-
In line
5, we have a paragraph tag for displaying text. -
In line
7, we write a button tag with anid=elemand functionchange(). 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 functionchange(), in which the click will call on the button fromHTMLpage. -
In line
11, we select the<button>element usingdocument.getElementById()and store it in a variable. -
In line
12, we apply the methodhasAttribute()on the variable which has thebuttonelement. 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()byconsole.log().
Output
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.