當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM setAttribute()用法及代碼示例

HTML DOM setAttribute() 方法用於獲取元素的屬性值。通過指定屬性的名稱,它可以設置該元素的值。如果該元素已經存在,則更新其值。

用法:

Object.setAttribute(attributename,value)

參數:該方法接受兩個參數:

  • attributename:它是一個要設置其值的字符串。
  • value:它是一個要分配給屬性名稱的字符串值。

返回值:該參數不返回任何值。

以下示例顯示了 setAttribute() 方法的使用。

示例 1:在此示例中,我們將使用 setAttribute() 方法向錨標記添加 href 屬性。

HTML


<!DOCTYPE html> 
<html> 
<body> 
    <h1 style="color:green"> 
        Geeks for Geeks 
    </h1> 
    <h2>setAttribute() Method</h2> 
  
    <a id="geek">Click to go to geeksforgeeks.org</a> 
  
    <p> 
        Click the button below to add an href 
        attribute to the element above. 
    </p> 
  
    <button onclick="myFunction()">Click Me</button> 
  
    <script> 
        function myFunction() { 
          document.getElementById("geek").setAttribute 
          ("href", "https://www.geeksforgeeks.org");  
        } 
    </script> 
</body> 
</html>

輸出:

HTML DOM setAttribute() Method

HTML DOM setAttribute() 方法

示例 2:在此示例中,我們將使用setAttribute()方法將輸入標簽的類型更改為按鈕。

HTML


<!DOCTYPE html> 
<html> 
<body> 
    <h1 style="color:green"> 
        Geeks for Geeks 
    </h1> 
    <h2>setAttribute() Method</h2> 
  
    <input id="geeks" value="Hello Geek"> 
  
    <p> 
        Click the button below to change the 
        input field to an input button. 
    </p> 
    <button onclick="changeType()">Change</button> 
  
    <script> 
        function changeType() { 
          document.getElementById("geeks").setAttribute("type", "button");  
        } 
    </script> 
</body> 
</html>

輸出:

HTML DOM setAttribute() Method

HTML DOM setAttribute() 方法

我們有 HTML DOM 方法的完整列表,要檢查這些方法,請閱讀這篇 HTML DOM 對象完整參考文章。

支持的瀏覽器:支持的瀏覽器DOM setAttribute() 方法如下:

  • 穀歌瀏覽器1.0
  • 互聯網瀏覽器5.0
  • 微軟邊12.0
  • 火狐1.0
  • Opera 8.0
  • Safari 1.0


相關用法


注:本文由純淨天空篩選整理自amitsingh2730大神的英文原創作品 HTML DOM setAttribute() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。