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

例如:

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

or

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

当前回答

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

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

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

其他回答

我发现需要使用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"

增加2个与.textContent和.innerHTML相关的点

<div id="mydiv"></div>


var elem = document.getElementById("mydiv");

elem.textContent = "hello"; // OK - Content has been updated
elem.setAttribute("textContent", "hello"); // NOT OK - You are trying to set
                                           // the attribute than it's content

elem.innerHTML = "world";   // OK - Content has been updated
elem.setAttribute("innerHTML", "world"); // NOT OK - You are trying to set
                                         // the attribute than it's content

谷歌API脚本对此进行了有趣的观察:

他们是这样做的:

var scriptElement = document.createElement("script");
scriptElement = setAttribute("src", "https://some.com");
scriptElement = setAttribute("nonce", "https://some.com");
scriptElement.async = "true";

注意,他们如何为"src"和"nonce"使用setAttribute,但是。async =…对于“async”属性。

我不是100%确定,但可能是因为“async”只在支持直接。attr =赋值的浏览器上被支持。因此,尝试setAttribute("async")是没有意义的,因为如果浏览器不理解.async=…它不会理解“async”属性。

希望这是我正在进行的“非最小化GAPI”研究项目的有益见解。如果我说错了,请指正。

这看起来像是使用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);
}

If the element you are referring to does not already include a Javascript object property for a given attribute (as others have described), then setting that property will not propagate the change back to the DOM, it just adds the named property to the Javascript object, and the DOM ignores it. For example, getting the element mySpan by id and then doing mySpan.class = 'warning' will do nothing, whether or not the span element in question already has a class attribute defined, because mySpan.class is not defined in the Javascript object for a span element. You have to use mySpan.setAttribute('class', 'warning').

然而,第二个细微差别是使用mySpan设置Javascript对象的innerHTML属性。setAttribute("innerHTML", someHTML)不会更新元素的内容。我不知道Javascript是如何捕获mySpan的。innerHTML = something,并调用HTML解析器,但在底层有一些神奇的东西。