HTML DOM Element setAttribute() 方法

定義和用法

setAttribute() 方法添加指定的屬性,并為其賦指定的值。

如果這個指定的屬性已存在,則僅設置/更改值。

注意:HTML 文檔的 HTMLElement 對象還定義了對應所有標準 HTML 屬性的 JavaScript 屬性。因此,只有您需要設置非標準屬性的時候,才需要使用該方法。

另請參閱:

參考手冊:

getAttribute() 方法

removeAttribute() 方法

hasAttribute() 方法

hasAttributes() 方法

getAttributeNode() 方法

setAttributeNode() 方法

removeAttributeNode() 方法

教程:

HTML 屬性

實例

例子 1

向元素添加 class 屬性:

element.setAttribute("class", "democlass");

添加之前:

Element 對象

添加之后:

Element 對象

親自試一試

例子 2

將輸入字段改為按鈕:

myInput.setAttribute("type", "button");

親自試一試

更改之前:

更改之后:

例子 3

向 <a> 元素添加 href 屬性:

myAnchor.setAttribute("href", "");

親自試一試

添加之前:

請訪問 codew3c.com

添加之后:

請訪問 codew3c.com

例子 4

將 target 屬性的值更改為 "_self":

if (element.hasAttribute("target")) {      
  element.setAttribute("target", "_self");
}

親自試一試

語法

element.setAttribute(name, value)

參數

參數 描述
name 必需。屬性的名稱。
value 必需。新的屬性值。

返回值

無。

拋出

異常 描述
INVALID_CHARACTER_ERR 參數 name 含有 HTML 屬性名或 XML 屬性名不允許使用的字符。
NO_MODIFICATION_ALLOWED_ERR 當前元素是只讀的,不允許修改它的屬性。

注意

可以為元素添加帶有值的 style 屬性,但不建議您這樣做,因為它會覆蓋 style 屬性中的其他屬性。

請改用 Style 對象的屬性:

劣:

element.setAttribute("style", "background-color:red;");

優:

element.style.backgroundColor = "red";

瀏覽器支持

element.setAttribute() 是 DOM Level 1 (1998) 特性。

所有瀏覽器都完全支持它:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 9-11 支持 支持 支持 支持