hasAttribute() in javascript

hasAttribute() method in javascript

hasAttribute() method is used to check and return whether an element has the specified attribute or not.

This method returns Boolean value.

Example - Check if an element has the attribute

Try Yourself

Example Explanation

  • In the above example we have created a button (idBtn) with attributes id, onclick and a Javascript function is declared for it (fun_name();).
  • When the button is clicked Javascript function is called.
  • In the Javascript function, first we are getting the button(getElementById("idBtn");) and storing in elem variable.
  • In the next step we are using the if.. else statement.
  • In the if statement we are checking if the elem variable has the id attribute.
  • Since the id attribute is present, it returns true and the alert statement inside if statement is executed (alert("Given attribute is present");).