MDN wants to talk to developers like you: https://qsurvey.mozilla.com/s3/8d22564490d8

Element.setAttributeNode()

setAttributeNode() 为指定的 Element 添加属性节点.

Syntax

var replacedAttr = element.setAttributeNode(attribute);
  • attribute是添加到 element 中的属性节点.
  • replacedAttr 是被替换掉的属性节点。 如果存在原有属性, 则函数返回原有属性节点. 

Example

// <div id="one" align="left">one</div> 
// <div id="two">two</div> 
var d1 = document.getElementById("one"); 
var d2 = document.getElementById("two"); 
var a = d1.getAttributeNode("align"); 
d2.setAttributeNode(a.cloneNode(true)); 
alert(d2.attributes[1].value) 
// returns: `left'

Notes

如果 element 中已经存在该属性名的属性,则函数使用新的属性替换掉原有的属性并将原有属性返回

这个方法很少被用到, 多数情况下使用函数 setAttribute() 修改 element 的属性.

DOM methods dealing with element's attributes:

Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used)
setAttribute (DOM 1) setAttributeNS setAttributeNode setAttributeNodeNS
getAttribute (DOM 1) getAttributeNS getAttributeNode getAttributeNodeNS
hasAttribute (DOM 2) hasAttributeNS - -
removeAttribute (DOM 1) removeAttributeNS removeAttributeNode -

Specification

DOM Level 2 Core: setAttributeNode (introduced in DOM Level 1 Core)

文档标签和贡献者

标签: 
 此页面的贡献者: Hearmen, FredWe
 最后编辑者: Hearmen,