Javascript Reference - HTML DOM id Property








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

Syntax

Return the id property:

var v = HTMLElementObject.id

Set the id property:

HTMLElementObject.id=id

Property Values

Value Description
id Specifies the id of an element

Return Value

A String type value representing the ID of an element.





Browser Support

id Yes Yes Yes Yes Yes

Example

The following code shows how to get the id of an element.


<!DOCTYPE html>
<html>
<body>
<p><a id="myAnchor" href="http://www.example.com/">example</a></p>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--   ww  w.  java2 s  . c  o m-->
    var x = document.getElementById("myAnchor").id;
    console.log(x);
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the id of an element.


<!DOCTYPE html>
<html>
<body>
<!-- w w  w. j  a  v  a  2s .co  m-->
<p><a id="myAnchor" href="http://www.example.com/">example</a></p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myAnchor").id = "newid";
    
}
</script>

</body>
</html>

The code above is rendered as follows: