Computer >> Computer tutorials >  >> Programming >> HTML

HTML DOM id Property


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 −

HTML DOM id Property

Click on “Show Id” button to display id of green paragraph.

HTML DOM id Property

Now, click on “Change Id” button to change id of green para from “Awesome-para” to “ID-Changed” −

HTML DOM id Property

We can check under “Inspect Element” as well −

HTML DOM id Property