HTML - DOM 屬性



HTML DOM 的attributes 屬性允許您訪問屬於 HTML 元素的屬性集合。此集合作為 NamedNodeMap 返回,允許您使用其名稱與屬性互動並檢索其值。

NamedNodeMap 是一個物件,它儲存元素屬性的集合。它允許我們透過名稱索引訪問屬性,並支援各種操作。

語法

以下是 HTML DOM 的attributes 屬性的語法:

node.attributes

引數

由於它是一個屬性,因此不接受任何引數。

返回值

此屬性返回包含 HTML 元素屬性集合的 'NameNodeMap',如果元素沒有屬性則返回 'null'

示例 1:修改 p 元素的屬性

以下示例演示了 HTML DOM 的attributes 屬性的用法。它修改了<p> 元素的內容:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM attributes</title>
<style>
   .highlight {
      background-color: yellow;
    }
</style>
</head>
<body>
<p></p>Modifies attributes of the P Element</p>
<p id="myParagraph">Example Text</p>
<button onclick="modifyParagraph()">Modify</button>
<script>
   function modifyParagraph() {
      var paragraph = document.getElementById("myParagraph");
      paragraph.setAttribute("title", "Modified"); 
      paragraph.textContent = "Modified Text";
      paragraph.classList.add("highlight");
    }
</script>
</body>
</html>

示例 2:檢查屬性是否存在

以下是 HTML DOM 的attributes 屬性的另一個示例。此屬性用於檢查段落元素上是否存在“title”屬性:

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Attributes</title>
</head>
<body>
</p>Checking for attribute Existence</p>
<p id="myParagraph" title="Example Title">Example Text</p>
<button onclick="checkAttributeExistence()">Check Attribute</button>  
<script>
   function checkAttributeExistence() {
      var paragraph = document.getElementById("myParagraph");
      var hasTitle = paragraph.hasAttribute("title");
      alert("Title Attribute Exists: " + hasTitle);
   }
</script>
</body>
</html>

示例 3:從 HTML 元素檢索屬性列表

下面的示例檢索並顯示 HTML <div> 元素的所有屬性。單擊按鈕時,所有屬性都將以列表格式顯示:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM attributes</title>
</head>
<body>
<div id="ex-Div"class="example" data-info="ex-data">
Hit the button to see the Div Elements...
</div>
<button onclick="showAttributes()">Show Attributes</button>
<ul id="attributeList"></ul>
<script>
   function showAttributes() {
      const element = document.getElementById('ex-Div');
      const attributeList = document.getElementById('attributeList');
      attributeList.innerHTML = '';
      for (let attr of element.attributes) {
         const li = document.createElement('li');
         li.textContent = `${attr.name}: 
         ${attr.value}`;
         attributeList.appendChild(li);
      }
   }
</script>
</body>
</html>    

示例 4:獲取特定屬性值

此示例從 ID 為“myParagraph”的段落元素中檢索 title 屬性的值,並在警報中顯示它:

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM attributes</title>
</head>
<body>
<p>Getting Specific Attribute</p>
<p id="myParagraph" title="Example Title">Example Text</p>
<button onclick="getAttributeValue()">Get Attribute Value</button>    
<script>
   function getAttributeValue() {
      var paragraph = document.getElementById("myParagraph");
      var titleValue =paragraph.getAttribute("title");
      alert("Title Attribute Value: " + titleValue);
   }
</script>
</body>
</html>

支援的瀏覽器

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