/

HTML / CSS / JavaScript Tutorial

JavaScript DOM HTML method: hasAttribute()

[this page | pdf | back links]

The hasAttribute() method (when applied to HTML elements in the JavaScript DOM) returns true if the element has the specified attribute, otherwise it returns false.

 

It has the following syntax with the following parameters. It returns a Boolean as above.

 

element.hasAttribute(attributename)

 

Parameter

Required / Optional

Description

attributename

Required

String containing name of attribute

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span><br>
<span id="element2"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width","150");
x2.setAttribute("height","70");
x2.setAttribute("style","border: 1px solid black");
var c2 = x2.getContext("2d");
c2.fillStyle = "blue";
c2.font = "40px Verdana";
c2.shadowBlur = "4";
c2.shadowColor = "red";
c2.shadowOffsetX = "2";
c2.shadowOffsetY = "3";
c2.fillText("Hello", 10, 50);
document.getElementById("element").appendChild(x2);

var a = x2.attributes;
var ct = a.length;
document.getElementById("element2").innerHTML = 
  "Has attributes? " + x2.hasAttributes() + "<br>" +
  "Has width attribute? " + x2.hasAttribute("width") + "<br>" +
  "Width attribute using getAttribute = " + x2.getAttribute("width") + "<br>" +
  "Number of attributes = " + ct + ", i.e.:<br>" +
  "&nbsp;" + a[0].name + " = " + a[0].value + "<br>" +
  "&nbsp;" + a[1].name + " = " + a[1].value + "<br>" +
  "&nbsp;" + a[2].name + " = " + a[2].value + "<br>";
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodDomHtmlHasAttribute() {
  var z = document.createElement("TABLE"); return !!z.hasAttribute;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile