咨询:使用Element.getAttributeNames替代Element.attributes的优劣及潜在问题
Element.getAttributeNames() vs Element.attributes: Pros and Cons Great question! Let's break down the tradeoffs of using Element.getAttributeNames() instead of directly working with Element.attributes—since MDN highlights the performance win but doesn't cover the potential downsides.
Pros of getAttributeNames()
- Better performance: As MDN notes, this method returns a static array of attribute names, whereas
Element.attributesgives you a liveNamedNodeMapcollection. Live collections have inherent overhead because they sync with DOM changes in real time—every time you access or iterate over them, the browser may re-query the DOM. The static array fromgetAttributeNames()is a snapshot, so iterating or manipulating it is faster and more predictable. - Cleaner, more intuitive code: Getting attribute names becomes a one-liner, and you can use all familiar array methods (
forEach,filter,map) right out of the box. Compare:
Usingattributes:
Usingconst attrNames = []; const attrs = element.attributes; for (let i = 0; i < attrs.length; i++) { attrNames.push(attrs[i].name); }getAttributeNames():const attrNames = element.getAttributeNames(); // Example: filter data attributes easily const dataAttrs = attrNames.filter(name => name.startsWith('data-')); - No unexpected live collection behavior: Since
NamedNodeMapis live, if the element's attributes change while you're iterating over it, you might get skipped or duplicated entries. The static array fromgetAttributeNames()avoids this entirely—it won't update even if the DOM changes later.
Cons of getAttributeNames()
- Browser compatibility gaps: This method is not supported in any version of Internet Explorer (including IE11). If your project needs to support legacy browsers, you'll have to stick with
Element.attributesor add a polyfill forgetAttributeNames(). - Extra overhead if you need attribute values: If your goal is to get both names and values,
Element.attributesgives youAttrobjects that include both properties in one go. WithgetAttributeNames(), you'd have to loop through the array and callelement.getAttribute(name)for each entry, which adds unnecessary steps (especially for elements with many attributes). - No built-in attribute manipulation: The
NamedNodeMapfromElement.attributesincludes methods likegetNamedItem(),setNamedItem(), andremoveNamedItem()to directly modify attribute nodes.getAttributeNames()only returns names—you'll need to use separate methods likesetAttribute()orremoveAttribute()if you want to make changes to the element's attributes.
内容的提问来源于stack exchange,提问作者Oscar Fabiani
相关产品推荐
相关产品推荐

