There is no way in vanilla JS to set multiple attributes on an element without writing each attribute to its own line. Writing them out as individual lines makes scanning the code more difficult to parse, as it appears less clearly grouped. There aren’t sneaky way around this either, like we can do with styles using Object.assign(element.style, {})
.
Therefore, I propose setAttribute
be extended to support an object, or that a new method like setAttributes
be created that allows developers to do this. I believe this would be a welcome and conservative improvement to the creation of DOM within JavaScript.
I wrote a hopefill for such functionality earlier this year, which you can test @ https://github.com/jonathantneal/element-set-attribute-object
FWIW, I would be happy to untie that script from the DOM, should its hopefill behavior inhibit any committees from considering it for inclusion.
Example usage
element.setAttribute({
id: 'nav-item-1',
class: 'nav-listitem',
ariaControls: 'nav-item-1-submenu',
ariaHaspopup: true,
ariaExpanded: false
})