简体   繁体   English

getAttribute() 与 Element 对象属性?

[英]getAttribute() versus Element object properties?

Expressions like Element.getAttribute("id") and Element.id return the same thing. Element.getAttribute("id")Element.id类的表达式返回相同的内容。

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?或者直接访问对象属性与使用这些属性方法对性能有什么影响?

getAttribute retrieves the attribute of a DOM element, while el.id retrieves the property of this DOM element. getAttribute检索 DOM 元素的属性,而el.id检索此 DOM 元素的属性 They are not the same.它们不一样。

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.hrefel.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.发生这种行为是因为根据W3C , href 属性必须是格式良好的链接。 Most browsers respect this standard (guess who doesn't?).大多数浏览器都尊重这个标准(猜猜谁不尊重?)。

There is another case for the input 's checked property. inputchecked属性还有另一种情况。 The DOM property returns true or false while the attribute returns the string "checked" or an empty string. DOM 属性返回truefalse而属性返回字符串"checked"或空字符串。

And then, there are some properties that are synchronized one-way only .然后,有一些属性是单向同步的。 The best example is the value property of an input element.最好的例子是input元素的value属性。 Changing its value through the DOM property will not change the attribute (edit: check the first comment for more precision).通过 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:实际上,只有两种情况需要使用属性:

  1. A custom HTML attribute, because it is not synced to a DOM property.自定义 HTML 属性,因为它未同步到 DOM 属性。
  2. 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 an input element).要访问未从属性同步的内置 HTML 属性,并且您确定需要该属性(例如, input元素的原始value )。

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).您只需花几分钟时间,但您会对这些信息感到高兴(我在这里总结了这些信息)。

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.但是, element.attribute可以返回属性的规范化或计算值。 Examples:例子:

  • <a href="/foo"></a>
    • a.href will contain full URL a.href 将包含完整的URL
  • <input type="checkbox" checked>
    • input.checked will be true (boolean) input.checked 将为真(布尔值)
  • <input type="checkbox" checked="bleh">
    • input.checked will be true (boolean) input.checked 将为真(布尔值)
  • <img src='http://dummyimage.com/64x64/000/fff'>
    • img.width will be 0 (number) before the image is loaded img.width 将在加载图像之前为 0(数字)
    • img.width will be 64 (number) when image (or first few bytes of it) is loaded加载图像(或图像的前几个字节)时,img.width 将为 64(数字)
  • <img src='http://dummyimage.com/64x64/000/fff' width="50%">
    • img.width will be the calculated 50% img.width 将是计算的50%
  • <img src='http://dummyimage.com/32x32/000/fff' style='width: 50px'>
    • img.width will be 50 (number) img.width 将为 50(数字)
  • <div style='background: lime;'></div>
    • div.style will be an object div.style 将是一个对象

.id saves the function call overhead. .id节省了函数调用开销。 (which is very small, but you asked. ) (这是非常小的,但你问过。)

According to this jsPerf test getAttribute is more slow than id property.根据这个 jsPerf 测试getAttributeid属性更慢。

PS聚苯乙烯

Oddly enough both statements perform very bad on IE8 (compared to other browsers).奇怪的是,这两个语句在 IE8 上的表现都非常糟糕(与其他浏览器相比)。

Always use the properties unless you have a specific reason not to.除非有特殊原因,否则请始终使用这些属性。

  • getAttribute() and setAttribute() are broken in older IE (and compatibility mode in later versions) getAttribute()setAttribute()在较旧的 IE 中被破坏(以及更高版本的兼容模式)
  • properties are more convenient (in particular, those corresponding to boolean attributes)属性更方便(特别是那些对应于布尔属性的)

There are some exceptions :一些例外

  • accessing attributes of <form> elements访问<form>元素的属性
  • accessing custom attributes (although I'd discourage using custom attributes at all)访问自定义属性(虽然我不鼓励使用自定义属性)

I've written about this subject a few times on SO:我在 SO 上写过几次关于这个主题的文章:

Try below example to understand this completely.尝试下面的例子来完全理解这一点。 For the below DIV对于下面的 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. Element.getAttribute('class')将返回myclass但您必须使用Element.className从 DOM 属性中检索它。

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.但是,可以使用 css 属性选择器选择具有使用setAttribute设置的自定义属性的 div,并相应地设置样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM