HTML DOM Element setAttribute()
示例
向元素新增一個 class 屬性
element.setAttribute("class", "democlass");
之前
Element 物件
之後
Element 物件
更多示例見下文。
描述
setAttribute()
方法為屬性設定新值。
如果屬性不存在,則首先建立它。
另請參閱
教程
語法
element.setAttribute(name, value)
引數
引數 | 描述 |
name | 必需。 屬性的名稱。 |
value | 必需。 新的屬性值。 |
返回值
無 |
不推薦
element.setAttribute("style", "background-color:red;");
推薦
element.style.backgroundColor = "red";
更多示例
向 <a> 元素新增 href 屬性
myAnchor.setAttribute("href", "https://w3schools.tw");
之前
前往 w3schools.com
之後
自己動手試一試 »將 target 屬性的值更改為 "_self"
if (element.hasAttribute("target")) {
element.setAttribute("target", "_self");
}
自己動手試一試 »
瀏覽器支援
element.setAttribute()
是 DOM Level 1 (1998) 的功能。
所有瀏覽器都完全支援。
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |