Javascript DOM HTML Element getAttribute() Method

Introduction

Get the value of the class attribute of an <h1> element:

var x = document.getElementsByTagName("H1")[0].getAttribute("class");

Click the button to display the value of the class attribute of the h1 element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {/*from  w  w  w.  j  a  v  a  2 s  .  c  o  m*/
  color: red;
}
</style>
</head>
<body>

<h1 class="democlass">Hello World</h1>
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementsByTagName("H1")[0].getAttribute("class");
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The getAttribute() method returns the value of the attribute by name, of an element.

Use the getAttributeNode() method to get the attribute as an Attr object.

element.getAttribute(attributename);

Parameter Values

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

The getAttribute() method returns a String, representing the specified attribute's value.

If the attribute does not exist, the return value is null or an empty string ("")




PreviousNext

Related