The HTML DOM id property returns and allow us to set id of an HTML element.
Syntax
Following is the syntax −
1. Returning id
object.id
2. Setting id
object.id=”value”
Here, “value” represents the id of an element.
Example
Let us see an example of id property −
<!DOCTYPE html> <html> <head> <style> p{ background-color:#347924; color:#fff; padding:8px; } .show{ margin:8px; color:#347924; font-size:18px; font-weight:bold; } </style> </head> <body> <h1>id property Example</h1> <p id="Awesome-para">This is a paragraph with some text and this para has an id "Awesome-para"</p> <button onclick="getId()">Show Id</button> <button onclick="changeId()">Change Id</button> <div class="show"></div> <script> function getId() { var paraId = document.querySelector('p').id; document.querySelector(".show").innerHTML = paraId; } function changeId() { document.querySelector('p').id = "ID-Changed"; document.querySelector(".show").innerHTML = 'new id is "ID-Chaged"'; } </script> </body> </html>
Output
This will produce the following output −
Click on “Show Id” button to display id of green paragraph.
Now, click on “Change Id” button to change id of green para from “Awesome-para” to “ID-Changed” −
We can check under “Inspect Element” as well −