Javascript getAttribute() 与 Element 对象属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10280250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getAttribute() versus Element object properties?
提问by P K
Expressions like Element.getAttribute("id")
and Element.id
return the same thing.
表达式 likeElement.getAttribute("id")
和Element.id
return 相同的东西。
Which one should be used when we need attributes of an HTMLElement object?
当我们需要 HTMLElement 对象的属性时应该使用哪一个?
Is there any cross browser issue with these methods like getAttribute()
and setAttribute()
?
这些方法是否有任何跨浏览器问题,例如getAttribute()
和setAttribute()
?
Or any impact on performance between directly accessing object properties vs using these attribute methods?
或者直接访问对象属性与使用这些属性方法对性能有什么影响?
回答by Florian Margaine
getAttribute
retrieves the attributeof a DOM element, while el.id
retrieves the propertyof this DOM element. They are not the same.
getAttribute
检索DOM 元素的属性,同时el.id
检索该 DOM 元素的属性。她们不一样。
Most of the time, DOM properties are synchronized with attributes.
大多数时候,DOM 属性与属性同步。
However, the synchronization does not guarantee the same value. A classic example is between el.href
and el.getAttribute('href')
for an anchor element.
但是,同步并不能保证相同的值。一个经典的例子是锚元素之间el.href
和el.getAttribute('href')
。
For example:
例如:
<a href="/" id="hey"></a>
<script>
var a = document.getElementById('hey')
a.getAttribute('href') // "/"
a.href // Full URL except for IE that keeps '/'
</script>
This behavior happens because according to the W3C, the href property must be a well-formed link. Most browsers respect this standard (guess who doesn't?).
发生这种行为是因为根据W3C, href 属性必须是格式良好的链接。大多数浏览器都尊重这个标准(猜猜谁不尊重?)。
There is another case for the input
's checked
property. The DOM property returns true
or false
while the attribute returns the string "checked"
or an empty string.
input
的checked
属性还有另一种情况。DOM 属性返回true
或false
而属性返回字符串"checked"
或空字符串。
And then, there are some properties that are synchronized one-way only. The best example is the value
property of an input
element. Changing its value through the DOM property will not change the attribute (edit: check the first comment for more precision).
然后,有一些属性是单向同步的。最好的例子是元素的value
属性input
。通过 DOM 属性更改其值不会更改该属性(编辑:检查第一条注释以获得更精确的信息)。
Because of these reasons, I'd suggest you keep using the DOM properties, and not the attributes, as their behavior differs between the browsers.
由于这些原因,我建议您继续使用 DOM属性,而不是属性,因为它们的行为因浏览器而异。
In reality, there are only two cases where you need to use the attributes:
实际上,只有两种情况需要使用属性:
- A custom HTML attribute, because it is not synced to a DOM property.
- To access a built-in HTML attribute, which is not synced from the property, and you are sure you need the attribute (for example, the original
value
of aninput
element).
- 自定义 HTML 属性,因为它未同步到 DOM 属性。
- 要访问一个内置的HTML属性,这是不是从属性同步,并且你确定你所需要的属性(例如,原来
value
的的input
元素)。
If you want a more detailed explaination, I strongly suggest you read this page. It will take you a few minutes only, but you will be delighted by the information (which I summed up here).
如果您想要更详细的解释,我强烈建议您阅读此页面。您只需花几分钟时间,但您会对这些信息感到高兴(我在这里总结了这些信息)。
回答by Salman A
getAttribute('attribute')
normally returns the attribute value as a string, exactly as defined in the HTML source of the page.
getAttribute('attribute')
通常以字符串形式返回属性值,与页面的 HTML 源代码中定义的完全相同。
However, element.attribute
could return a normalized or calculated value of the attribute. Examples:
但是,element.attribute
可以返回属性的规范化或计算值。例子:
<a href="/foo"></a>
- a.href will contain fullURL
<input type="checkbox" checked>
- input.checked will be true (boolean)
<input type="checkbox" checked="bleh">
- input.checked will be true (boolean)
<img src='http://dummyimage.com/64x64/000/fff'>
- img.width will be 0 (number) before the image is loaded
- img.width will be 64 (number) when image (or first few bytes of it) is loaded
<img src='http://dummyimage.com/64x64/000/fff' width="50%">
- img.width will be the calculated50%
<img src='http://dummyimage.com/32x32/000/fff' style='width: 50px'>
- img.width will be 50 (number)
<div style='background: lime;'></div>
- div.style will be an object
<a href="/foo"></a>
- a.href 将包含完整的URL
<input type="checkbox" checked>
- input.checked 将为真(布尔值)
<input type="checkbox" checked="bleh">
- input.checked 将为真(布尔值)
<img src='http://dummyimage.com/64x64/000/fff'>
- img.width 将在加载图像之前为 0(数字)
- 加载图像(或图像的前几个字节)时,img.width 将为 64(数字)
<img src='http://dummyimage.com/64x64/000/fff' width="50%">
- img.width 将是计算的50%
<img src='http://dummyimage.com/32x32/000/fff' style='width: 50px'>
- img.width 将为 50(数字)
<div style='background: lime;'></div>
- div.style 将是一个对象
回答by gdoron is supporting Monica
.id
saves the the function call overhead. (which is very small, but you asked. )
.id
节省了函数调用开销。(这是非常小的,但你问过。)
回答by mamoo
According to this jsPerf testgetAttribute
is more slow than id
property.
根据这个 jsPerf 测试getAttribute
比id
属性更慢。
PS
聚苯乙烯
Oddly enough both statements perform very bad on IE8 (compared to other browsers).
奇怪的是,这两个语句在 IE8 上的表现都非常糟糕(与其他浏览器相比)。
回答by Tim Down
Always use the properties unless you have a specific reason not to.
除非有特殊原因,否则请始终使用这些属性。
getAttribute()
andsetAttribute()
are broken in older IE (and compatibility mode in later versions)- properties are more convenient (in particular, those corresponding to boolean attributes)
getAttribute()
并setAttribute()
在较旧的 IE 中损坏(以及更高版本中的兼容模式)- 属性更方便(特别是那些对应于布尔属性的)
There are some exceptions:
有一些例外:
- accessing attributes of
<form>
elements - accessing custom attributes (although I'd discourage using custom attributes at all)
- 访问
<form>
元素的属性 - 访问自定义属性(虽然我不鼓励使用自定义属性)
I've written about this subject a few times on SO:
我在 SO 上写过几次关于这个主题的文章:
回答by Hrushikesh
Try below example to understand this completely. For the below DIV
尝试下面的例子来完全理解这一点。对于下面的 DIV
<div class="myclass"></div>
<div class="myclass"></div>
The Element.getAttribute('class')
will return myclass
but you have to use Element.className
which retrieves it from the DOM property.
The Element.getAttribute('class')
will returnmyclass
但您必须使用Element.className
which 从 DOM 属性中检索它。
回答by Jsilvermist
One area where this makes a big difference is with css styling based on attributes.
这产生很大差异的一个领域是基于属性的 css 样式。
Consider the following:
考虑以下:
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>
The div with the custom property set directly doesn't reflect the value to the attribute, and is not selected by our attribute selector (div[custom]
) in the css.
直接设置自定义属性的 div 不会将值反映到属性中,也不会被我们div[custom]
的 css 中的属性选择器 ( )选中。
The div with the custom attribute set using setAttribute
, however, is able to be selected using a css attribute selector, and styled accordingly.
setAttribute
但是,使用 设置自定义属性的 div可以使用 css 属性选择器进行选择,并相应地设置样式。