The id
property sets or gets the id in id attribute of an element.
Return the id property:
var v = HTMLElementObject.id
Set the id property:
HTMLElementObject.id=id
Value | Description |
---|---|
id | Specifies the id of an element |
A String type value representing the ID of an element.
id |
Yes | Yes | Yes | Yes | Yes |
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:
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: