Check if a web element has a specific property and apply changes to the DOM according to the property's existence I wrote this Javascript snippet for a Polymer fronted, it works without issues.

The only thing that it accomplishes is changing an icon's orientation whenever a user is clicking on any expandable-item (expandable-item is a specific Tag name).

Imagine a classic Operating System's folder tree display and the + or - icon that shows if a specific folder is expandable or not.

When the user clicks, the clicked expandable-item tag receives the expanded attribute.

The user can click on several expandable-item and all of them must remain opened or closed according to the user clicks and, clearly, also the icons related to the items must change accordingly.

Are there any ways that you could suggest to make it more efficient and/or shorter?

var expandedItems = this.shadowRoot.querySelectorAll('expandable-item');

for (var i = 0; i &lt; expandedItems.length; ++i) {
    if (expandedItems[i].hasAttribute("expanded")){
        expandedItems[i].getElementsByClassName("expandable-icon")[0].setAttribute("icon", "arrow:chevron-open-down");
    } else {
        expandedItems[i].getElementsByClassName("expandable-icon")[0].setAttribute("icon", "arrow:chevron-open-right");
    }
}


Thanks for your suggestions.
Search online for "queryselectorall vs getelementsbytagname" and you will likely see results like this SO post from August 2013 and this post from September 2010. After reading those one can posit that using Element.getElementsByTagName() instead of querySelectorAll() would be quicker, since the selector appears to merely find elements by tag name. Be aware that method returns a Live HTMLCollection so you would need to put the elements into an array before iterating over them. There are some nice tools in ecmascript-6 to do this, like using the spread syntax or calling Array.from().



If you keep the for loop, you could consider using a for...of (also standard with ecmascript-6) in order to eliminate the accessing array elements with bracket notation.



I am not able to find references to those attributes icon="arrow:chevron-open-down" and icon="arrow:chevron-open-right" but if those could be handled in CSS then you could eliminate the whole JS iteration block.