Current, if you want to set multiple styles on an element using JS, you have to set them one at a time. What I’m proposing is a styles
property that is set with a JSON object. This can be achieved pretty easily in vanilla JS:
Object.defineProperty(Object.prototype, 'styles', {
enumerable: true,
configurable: false,
get: function() { return this.style; },
set: function(param) {
if(this instanceof HTMLCollection) {
for(i=0; i<this.length; i++) {
for(key in param) {
key = key.replace(/-[a-z]/g, "$&".toUpperCase() );
this[i].style[key] = param[key];
}
}
}
else if(this instanceof HTMLElement) {
for(key in param) {
key = key.replace(/-[a-z]/g, "$&".toUpperCase() );
this.style[key] = param[key];
}
}
}
});
Obviously it would be implemented in ES6, rather than including that piece of code, but it shows how it could be done with current JS capabilities.
Proposed usage:
document.getElementById("foo").styles = {
"background-color" : "red",
"border" : "3px solid purple",
"color" : "grey"
};
With the code block I included above, it would also work on iterable objects (returned by document.getElementsByClassName
). It also uses regex to replace hyphens with the camelCase version, although that’s just because of the fact that it’s done using vanilla JS. Obviously that wouldn’t be necessary in a full implementation.
Thoughts?