Copy a Style from One Element to Another using JS

avatar

Borislav Hadzhiev

Sat Jan 08 20222 min read

Copy a Style from One Element to Another using JS #

To copy a style from one element to another:

  1. Use the window.getComputedStyle() method to get an object of the element's styles.
  2. Assign the specific styles to the other element's style object.

Here is the HTML for the examples in this article.

index.html
<!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.

index.js
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.

We used the getComputedStyle method and not the style object, because thegetComputedStyle method takes external stylesheets into consideration.

The last step is to use the style object to assign the specific CSS properties to the element.

Note that multi-word properties are camel-cased on the 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.

styles applied successfully

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee