This snippet shows a way to add getters and setters to a specific key of an existing object. This is powerful for decorating configuration objects with special behaviors. This kind of thing can easily be created with a little more abstraction:
I’m thinking about adding a little fake console to the Snippet Zone Quick Editor – just whipped this up as a proof of concept – something like this should work…
// hacky way to set many attributes - just for fun
const el = document.body.appendChild(
document.createElement('button'));
let i, a;
el.innerHTML='hello';
for(i in a ={
id:'xyz',
title:'hi there...',
style: `
background: red;
color:white;
font-size: 1.4em;
`
}) el.setAttribute(i, a[i]);
Chances are you don’t want to use this unless you are just speed coding, prototyping or playing around
If you do want to set multiple attributes, you’ll likely be doing so in an abstract way with one of the many popular js libs or frameworks.
In my personal projects I usually don’t use DOM related libs or frameworks, so I do this or something like it:
function attrs(el, attrs){
for(let i in attrs){
el.setAttribute(i, attrs[i])
}
}
I’ll always miss jQuery, used it for many years and found it extremely intuitive and a huge time saver… The above attrs function is just a crappier version of the jQuery attr method. Read more about that here in the docs.