像 Element.getAttribute("id")
和 Element.id
这样的表达式返回相同的结果。
当我们需要 HTMLElement 对象的属性时,应该使用哪一个?
这些方法(如 getAttribute()
和 setAttribute()
)是否存在跨浏览器问题?
或者直接访问对象属性与使用这些属性方法之间是否有性能影响?
像 Element.getAttribute("id")
和 Element.id
这样的表达式返回相同的结果。
当我们需要 HTMLElement 对象的属性时,应该使用哪一个?
这些方法(如 getAttribute()
和 setAttribute()
)是否存在跨浏览器问题?
或者直接访问对象属性与使用这些属性方法之间是否有性能影响?
getAttribute
方法可以获取 DOM 元素的属性,而 el.id
则可以获取该 DOM 元素的属性值。它们并不相同。el.href
和 el.getAttribute('href')
。<a href="/" id="hey"></a>
<script>
var a = document.getElementById('hey')
a.getAttribute('href') // "/"
a.href // Full URL except for IE that keeps '/'
</script>
input
元素的原始value
)。如果您想要更详细的解释,我强烈建议您阅读此页面。这只需要几分钟时间,但您将对信息感到高兴(我在这里总结了信息)。
a.href
返回完整的 URL,而 a.getAttribute("href")
返回 HTML 源代码中定义的属性。 - Salman AgetAttribute('attribute')
通常会返回属性值的字符串,在页面的HTML源代码中定义的内容一致。
然而,element.attribute
可能返回属性的规范化或计算值。例如:
<a href="/foo"></a>
<input type="checkbox" checked>
<input type="checkbox" checked="bleh">
<img src='http://dummyimage.com/64x64/000/fff'>
<img src='http://dummyimage.com/64x64/000/fff' width="50%">
<img src='http://dummyimage.com/32x32/000/fff' style='width: 50px'>
<div style='background: lime;'></div>
.id
可以节省函数调用开销(虽然很小,但您提出了这个问题。)
除非您有特定原因不使用属性,否则请始终使用属性。
getAttribute()
和setAttribute()
在旧版IE(以及后期版本的兼容性模式)中存在问题以下是一些例外情况:
<form>
元素的属性我在SO上几次写过这个主题:
<div class="myclass"></div>
Element.getAttribute('class')
将返回myclass
,但您必须使用Element.className
从DOM属性中检索它。这种情况对基于属性的CSS样式设置有很大影响。
请考虑以下内容:
const divs = document.querySelectorAll('div');
divs[1].custom = true;
divs[2].setAttribute('custom', true);
div {
border: 1px solid;
margin-bottom: 8px;
}
div[custom] {
background: #36a;
color: #fff;
}
<div>A normal div</div>
<div>A div with a custom property set directly.</div>
<div>A div with a custom attribute set with `setAttribute`</div>
直接设置自定义属性的 div 不会反映到属性值,并且在 CSS 中无法通过属性选择器 (div[custom]
) 进行选择。
然而,使用 setAttribute
设置自定义属性的 div 可以被 CSS 属性选择器选择并进行相应的样式设置。