HTML DOM Element setAttribute() Metodong
- 上一页 scrollWidth
- 下一页 setAttributeNode()
- 返回上一层 HTML DOM Elements 对象
Paglilinaw at Paggamit
setAttribute()
Ang metodong ito ay magdagdag ng tinukoy na attribute at magbibigay ng tinukoy na halaga.
Kung ang tinukoy na attribute ay umiiral na, magtatakda lamang ng pagbabago sa halaga.
Pansin:Ang HTMLElement ng HTML dokumento ay naglalagay din ng JavaScript attribute para sa lahat ng standard na HTML attribute. Kaya, kailangan lamang gamitin ang metadong ito kapag kailangan mong itakda ang hindi standar na attribute.
Mga ibang sanggunian:
Mga Sanggunian ng Pamamahala:
removeAttributeNode() Metodong
Tuturuan:
Eksemplo
Halimbawa 1
Magdagdag ng class attribute sa elemento:
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 | 支持 | 支持 | 支持 | 支持 |
- 上一页 scrollWidth
- 下一页 setAttributeNode()
- 返回上一层 HTML DOM Elements 对象