Borislav Hadzhiev
Sat Jan 08 2022·2 min read
Photo by Allef Vinicius
To copy a style from one element to another:
window.getComputedStyle()
method to get an object of the element's
styles.style
object.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> #box { font-size: 2rem; color: white; margin-bottom: 10px; } </style> </head> <body> <div id="box" style="background-color: salmon; width: 150px; height: 150px"> Box content </div> <div id="another">Another Box</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.getElementById('box'); const another = document.getElementById('another'); const boxStyles = window.getComputedStyle(box); another.style.backgroundColor = boxStyles.backgroundColor; another.style.color = boxStyles.color; another.style.width = boxStyles.width; another.style.height = boxStyles.height;
If you need to copy ALL styles from one element to another, check out my other article - Copy all Styles from one Element to Another using JS.
The window.getComputedStyle method returns an object containing the values of all CSS properties of the element.
getComputedStyle
method and not the style
object because the getComputedStyle
method takes external stylesheets into consideration.The last step is to use the style
object to assign the specific CSS properties
to the element.
style
object, as well as on the object the getComputedStyle()
method returns.If I open my browser, I can see that the styles have been applied to the other element.
If you need to copy ALL styles from one element to another, check out my other article - Copy all Styles from one Element to Another using JS.