HTML - DOM id Property



The HTML DOM id property is used to set and retrieve the value of an element's id attribute. This property allows you to uniquely identify an element within the document, which can be used for styling with CSS or accessing specific elements in JavaScript through the getEleementById() method.

Syntax

Following is the syntax of the HTML DOM id (to set the id property) property −

element.id = id_name

Where, id_name specifies the id attribute of an element.

To get the id property value, use the following syntax −

element.id

Parameters

Since, it is a property, it does not accept any parameters.

Return Value

This property returns a string that represents the id attribute of the element.

Example 1: Get the id of the first Div

The following is the basic example of the HTML DOM id property −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM id</title>
</head>
<body>
<p>Click the button to get the ID of the first div element.</p>
<div id="firstDiv">First Div</div>
<div id="secondDiv">Second Div</div> 
<br>
<button onclick="getIdOfFirstDiv()">Get ID of First Div</button>
<p id="message"></p>
<script>
   function getIdOfFirstDiv() {
      const message = document.getElementById('message');
      message.textContent = `The ID of the first div is: ${firstDiv.id}`;
   }
</script>
</body>
</html>

Example 2: Changing ID of an Element

Following is another example of the HTML DOM id property. We use this property to change the existing id value "myElement" to a new "newElementId" value −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM id</title>
</head>
<body>
<p>Click the buttacon to change the ID.</p>
<button onclick="changeId()">Change ID</button>
<div id="myElement">Element with ID "myElement"</div>
<div id="result"></div>
<script>
   function changeId() {
      const element = document.getElementById('myElement');
      const resultElement = document.getElementById('result');
      element.setAttribute('id', 'newElementId');
      resultElement.textContent = 'ID changed successfully to "newElementId"';
  }
</script>
</body>
</html>    

Example 3: Toggling Visibility Based on ID

The example below helps us understand how to control actions based on an element's ID. This example includes a <div> element that becomes visible when a button is clicked, revealing its content by ID −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM id</title>
<style>
   #td {
      display: none;
   }
</style>
</head>
<body>
<p>Enable visibility of the <div>element based on its ID.</p>
<button onclick="toggleVisibility()">Toggle Visibility</button>
<div id="td">
<p>This div is toggled based on its ID.</p>
</div>
<script>
   function toggleVisibility() {
   const div = document.getElementById('td');
   div.style.display = (div.style.display === 'none') ? 'block' : 'none';
   }
</script>
</body>
</html>    

Supported Browsers

Property Chrome Edge Firefox Safari Opera
id Yes Yes Yes Yes Yes
html_dom.htm
Advertisements