Setting multiple styles of an HTML element with vanilla JavaScript often requires multiple lines of code.
However, we can do it all with one line of code if we put our wrap our object styles in a JavaScript proxy.
In this article, we’ll look at how we can wrap our element object in a proxy to let set multiple styles.
Set Multiple Styles Easily by Wrapping Our Element in a Proxy
To wrap our HTML element object in a proxy, we can write:
const styleProxy = {
get: (object, property) => {
return (value) => {
if (value) {
object[property] = value;
return new Proxy(object, styleProxy);
}
return object[property];
}
}
}
const style = (selector) => {
const element = document.querySelector(selector);
return new Proxy(element.style, styleProxy);
}
style("div")
.color("#fff")
.backgroundColor("#000")
.opacity("1");
We create the styleProxy
object that has the get
method to return a function that takes the style value
.
If we pass in a value
, then we set it as one of the property value of object
.
Then we return the proxy with the object
and styleProxy
as the proxy.
Otherwise, we return the object.
Next, we create the style
that gets element with the given selector with querySelector
and return a proxy with element.style
object property and styleProxy
.
The proxy lets us get the value that we set as the value of a property of an object and modify how it’s set.
In this example, we return a function that lets us set the property with the function instead of the object itself.
Therefore, we can write the following to set the styles:
style("div")
.color("#fff")
.backgroundColor("#000")
.opacity("1");
We call color
to set style.color
.
We call backgroundColor
to set style.backgroundColor
.
And we call opacity
to set style.opacity
.
Conclusion
We can set multiple styles in one line of code by creating a proxy from the selected HTML element object.
In the proxy, we have a getter that returns a function that returns a new proxy to set other styles.