是否已经开发了使用setAttribute代替点(.)属性表示法的最佳实践?

例如:

myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");

or

myObj.className = "nameOfClass";
myObj.id = "someID";

当前回答

在元素上设置属性(例如class)的方法: 1. 埃尔。className = string 2. el.setAttribute(‘类’,字符串) 3.el.attributes.setNamedItem(对象) 4. el.setAttributeNode(节点)

我做了一个简单的基准测试(这里)

似乎setAttributeNode比使用setAttribute快3倍。

所以如果性能是一个问题-使用“setAttributeNode”

其他回答

如果您希望在JavaScript中进行编程访问,您应该始终使用直接的.attribute形式(但请参阅下面的quirksmode链接)。它应该正确地处理不同类型的属性(想想“onload”)。

使用getAttribute/setAttribute当你希望处理DOM,因为它是(例如,文字文本)。不同的浏览器会混淆这两者。参见怪癖模式:属性(在)兼容性。

两者之间的一个区别是setAttribute,当用于设置<input/>的值时,将使该值成为它所在表单上调用.reset()时的默认值,但.value =不会这样做。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset

注意,如果调用setAttribute()来设置特定属性的值,则后续调用reset()不会将该属性重置为其默认值,而是将该属性保持setAttribute()调用设置的值。

来自Javascript: The Definitive Guide,它澄清了一些事情。它注意到HTML文档的HTMLElement对象定义了与所有标准HTML属性对应的JS属性。

因此,您只需要对非标准属性使用setAttribute。

例子:

node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works

这看起来像是使用setAttribute更好的一种情况:

高效的JavaScript

var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
    'border: ' + newBorder + ';';
if(typeof(posElem.style.cssText) != 'undefined') {
    posElem.style.cssText = newStyle;
} else {
    posElem.setAttribute('style', newStyle);
}

我发现需要使用setAttribute的一种情况是在更改ARIA属性时,因为没有相应的属性。例如

x.setAttribute('aria-label', 'Test');
x.getAttribute('aria-label');

没有x。arialabel之类的东西,所以你必须使用setAttribute。

编辑:x["aria-label"]不工作。你确实需要setAttribute。

x.getAttribute('aria-label')
null
x["aria-label"] = "Test"
"Test"
x.getAttribute('aria-label')
null
x.setAttribute('aria-label', 'Test2')
undefined
x["aria-label"]
"Test"
x.getAttribute('aria-label')
"Test2"