HTML - DOM id 屬性



HTML DOM 的id屬性用於設定和檢索元素id屬性的值。此屬性允許您唯一地標識文件中的元素,這可用於CSS樣式或透過getEleementById()方法在JavaScript中訪問特定元素。

語法

以下是HTML DOM 的id(設定id屬性)屬性的語法:

element.id = id_name

其中,id_name指定元素的id屬性。

要獲取id屬性值,請使用以下語法:

element.id

引數

因為它是一個屬性,所以它不接受任何引數。

返回值

此屬性返回一個字串,表示元素的id屬性。

示例 1:獲取第一個 Div 的 id

以下是HTML DOM 的id屬性的基本示例:

<!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>

示例 2:更改元素的 ID

以下是HTML DOM 的id屬性的另一個示例。我們使用此屬性將現有id值“myElement”更改為新的“newElementId”值:

<!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>    

示例 3:根據 ID 切換可見性

下面的示例幫助我們瞭解如何根據元素的 ID 控制操作。此示例包含一個<div>元素,當單擊按鈕時,它會變為可見,透過 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>    

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
id
html_dom_element_reference.htm
廣告