Javascript DOM HTML Element hasAttribute() Method

Introduction

Find out if a <button> element has an onclick attribute:

var x = document.getElementById("myBtn").hasAttribute("onclick");

Click the button to find out if the button element has an onclick attribute.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button id="myBtn" onclick="myFunction()">Test</button>
<p id="demo"></p>

<script>
function myFunction() {//  w  ww  .  j a v a2 s . com
  var x = document.getElementById("myBtn").hasAttribute("onclick");
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The element.hasAttribute() method returns true if the specified attribute exists, otherwise it returns false.

Use element.setAttribute() to add a new attribute or change the value of an existing attribute on an element.

element.hasAttribute(attributename);

Parameters

Parameter Type Description
attributename String Required. The name of the attribute you want to check if exists



PreviousNext

Related