Javascript Reference - HTML DOM Anchor id Property








The id property sets or gets the value of the id attribute of a link.

Browser Support

id Yes Yes Yes Yes Yes

Syntax

Return the id property:

var v = anchorObject.id 

Set the id property:

anchorObject.id = id;

Property Values

Value Description
id Set the id of a link




Return Value

A String representing the id of the link.

Example

The following code shows how to get the id of a link.


<!DOCTYPE html>
<html>
<body>
<!--from  ww w . ja va2s  . com-->
<p><a id="myAnchor" href="http://www.example.com/">example</a></p>
<button onclick="myFunction()">test</button>

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

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").id;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the id of a link.


<!DOCTYPE html>
<html>
<body>
<!--from  w ww .ja  v a2  s. com-->
<p><a id="myAnchor" href="http://www.example.com/">example</a></p>
<button onclick="myFunction()">test</button>

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

<script>
function myFunction() {
    document.getElementById("myAnchor").id = "newid";
    document.getElementById("demo").innerHTML = "changed";
}
</script>

</body>
</html>

The code above is rendered as follows: