Javascript DOM HTML Element id Property get

Introduction

Get the id of an element:

var x = document.getElementsByClassName("anchors")[0].id;

Click the button to display the value of the id attribute of the first link above.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.anchors {/*from w  w  w .j a v a2s.  c o  m*/
  display: block;
  padding: 5px;
  background-color: black;
  color: white;
}

#myAnchor {
  background-color: dodgerblue;
}
</style>
</head>
<body>

<a class="anchors" id="myAnchor" href="https://www.java2s.com/">HTML</a>
<a class="anchors" href="https://www.java2s.com/">CSS</a>
<a class="anchors" href="https://www.java2s.com/">JavaScript</a>


<button onclick="myFunction()">Test</button>

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

<script>
function myFunction() {
  var x = document.getElementsByClassName("anchors")[0].id;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The id property sets or gets the id of an element.

The id property reflects the value of an element's id attribute.

An ID should be unique within a page.




PreviousNext

Related