HTML - getAttribute() 方法



HTML DOM 的getAttribute() 方法用於獲取屬於 HTML 元素的指定屬性的值。如果給定的屬性不存在,則返回的值將為“null”。

語法

以下是 HTML DOM getAttribute() 方法的語法:

element.getAttribute(attributeName)

引數

此方法接受如下所示的單個引數:

引數 描述
attributeName 要檢索其值的屬性的名稱。

返回值

此方法返回一個字串,其中包含指定屬性的值。如果屬性不存在,則返回“null”。

示例 1:訪問和顯示“href”屬性

以下是 HTML DOM getAttribute() 方法的基本示例。它從錨元素 (<a>) 獲取href 屬性:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM getAttribute()</title>
</head>
<body>
<h4>Retrieves the value of href attribute</h4> 
<a id="myLink" href="https://tutorialspoint.tw">Example Link</a>
<div id="output"></div>
<script>
   // Selecting the anchor element by ID
   const myLink = document.getElementById('myLink');
   const hrefVal = myLink.getAttribute('href');
   // Displaying the result
   const od= document.getElementById('output');
   od.textContent = `Link URL: ${hrefVal}`;
</script>
</body>     
</html>    

示例 2:獲取 HTML 元素的屬性值

以下是 HTML DOM getAttribute() 方法的另一個示例。我們使用此方法獲取<div> 元素中所有可用的屬性:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM getAttribute()</title>
</head>
<body>
<div id="myElement" class="box" 
data-info="example data">
<p>This is a paragraph inside a div element.</p>
<a href="https://tutorialspoint.tw">Example Link</a>
</div>
<div id="output"></div>
<script>
   // Selecting the element by ID
   const my= document.getElementById('myElement');
   //Retrieving attribute values
   const cv = my.getAttribute('class');
   const dInv = my.getAttribute('data-info');
   const hv = my.querySelector('a').getAttribute('href');
   // Displaying the results
   const od = document.getElementById('output');
   od.innerHTML = `
       <p>Class attribute value: ${cv}</p>
       <p>Data-info attribute value: ${dInv}</p>
       <p>Anchor href attribute value: ${hv}</p>
   `;
</script>
</body>
</html>    

示例 3:獲取按鈕屬性

此示例顯示了 DOM getAttribute() 方法的用法,用於訪問和顯示 HTML <button> 元素的 onclick 屬性的值:

<!DOCTYPE html>
<html lang="en">
<head>  
<title>HTML DOM getAttribute()</title>
</head>
<body>
<h4>Retrieves the value of Button attribute</h4> 
<button id="myB" onclick="displayMessage()">Click me</button>
<div id="ot"></div>
<script>
   function displayMessage() {
      const ocv = document.getElementById
      ('myB').getAttribute('onclick');
      document.getElementById('ot').textContent = `Value of onclick attribute: ${ocv}`;
   }
</script>
</body>
</html>    

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
getAttribute()
html_dom_element_reference.htm
廣告