Sometimes, we want to set or copy JavaScript computed style from one element to another.
In this article, we’ll look at how to set or copy JavaScript computed style from one element to another.
How to set or copy JavaScript computed style from one element to another?
To set or copy JavaScript computed style from one element to another, we can loop through each style and call the setProperty
method to set the styles on the target element.
For instance, we write:
<div style='background-color: green; height: 100px; width: 100px'>
</div>
<section></section>
to add a div and a section element.
Then we copy the styles of the div to the section element by writing:
const copyNodeStyle = (sourceNode, targetNode) => {
const computedStyle = window.getComputedStyle(sourceNode);
for (const key of computedStyle) {
targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key))
}
}
const div = document.querySelector('div')
const section = document.querySelector('section')
copyNodeStyle(div, section)
We define the copyNode
function that takes the sourceNode
and targetNode
.
In it, we get the sourceNode
‘s styles with window.getComputedStyle
.
Then we loop through the computedStyle
iterable object with the for-of loop.
We get the style from the sourceNode
with computedStyle.getPropertyValue(key)
.
And we get the priority of the style with computedStyle.getPropertyPriority(key)
.
Then we set the styles with setProperty
.
As a result, we see that the section element has the same styles as the div after the loop is run.
Conclusion
To set or copy JavaScript computed style from one element to another, we can loop through each style and call the setProperty
method to set the styles on the target element.