Javascript Reference - HTML DOM hasAttribute() Method








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

Browser Support

hasAttribute Yes 9 Yes Yes Yes

Syntax

element.hasAttribute(attributename)

Parameters

Parameter Type Description
attributename String Required. The name of the attribute to check




Return Value

It returns a Boolean type value.

true if the element has attributes, otherwise false.

Example

The following code shows how to check if the button element has an onclick attribute.


<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!--from   w  w  w . j a  v  a2s .  c  o m-->
{
    var btn=document.getElementsByTagName("BUTTON")[0];
    var x=document.getElementById("demo");
    x.innerHTML=btn.hasAttribute("onclick");
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code uses hasAttribute to check the existence of an attribute.

<!DOCTYPE HTML> 
<html> 
<body> 
<p id="textblock" class="Survey numbers"> 
    This is a test.              <!-- ww w  .jav a 2  s  .  c o m-->
</p> 
<pre id="results"></pre> 
<script> 
    var elem = document.getElementById("textblock"); 
    document.writeln("lang attribute: " + elem.hasAttribute("lang")); 
    elem.setAttribute("lang", "en-US"); 
    document.writeln("Attr value is : " + elem.getAttribute("lang")); 
    elem.setAttribute("lang", "en-UK"); 
    document.writeln("Value is now: " + elem.getAttribute("lang")); 
</script> 
</body> 
</html>

Click to view the demo