Copy all Styles/Attributes from one Element to Another in JS

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
5 min

banner

# Table of Contents

  1. Copy all Styles from one Element to Another using JS
  2. Copy specific Style from One Element to Another using JS
  3. Copy all Attributes from one Element to Another using JS

# Copy all Styles from one Element to Another using JS

To copy all styles from one element to another:

  1. Create the other element using the document.createElement() method.
  2. Get a string containing the styles of the original element.
  3. Assign the CSS string as cssText on the newly created element.

Here is the HTML for the examples.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> #box { font-size: 2rem; color: white; margin-top: 10px; } </style> </head> <body> <div id="box" style=" background-color: salmon; width: 150px; height: 150px; " > Box content </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // ๐Ÿ‘‡๏ธ Create another element const another = document.createElement('div'); another.innerHTML = 'Another content'; // ๐Ÿ‘‡๏ธ Get computed styles of original element const styles = window.getComputedStyle(box); let cssText = styles.cssText; if (!cssText) { cssText = Array.from(styles).reduce((str, property) => { return `${str}${property}:${styles.getPropertyValue( property, )};`; }, ''); } // ๐Ÿ‘‡๏ธ Assign CSS styles to the element another.style.cssText = cssText; // ๐Ÿ‘‡๏ธ (optionally) add the element to the DOM document.body.appendChild(another);
The code for this article is available on GitHub

We used the createElement() method to create a div element.

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 property because the getComputedStyle method takes external stylesheets into consideration and resolves computations contained by the values.

The cssText property returns the text of the element's styles, however, it is not supported by all browsers and sometimes returns an empty string.

If the property is not supported, we iterate over the computed styles to manually create the string that contains the element's styles.

The function we passed to the Array.reduce() method gets called with each element in the array (CSS style property name).

We passed an empty string as the initial value for the str variable.

On each iteration, we append the current CSS property name and its value to the accumulated string and return the result.

The value we return from the callback function gets passed as the str variable in the next iteration.

After the last iteration, the cssText variable contains a string with all of the styles of the original element.

The last step is to assign the string to the element's style.cssText property.

You can optionally use the appendChild() method to add the node to the end of the list of children of the element on which the method was invoked.

In the example, we called the appendChild() method on the body element, but this could be any other node.

If I open the page from the example, I can see that the styles from the first element have been successfully applied to the second.

styles applied to other element

And the elements look identical in my browser.

elements look identical

# Copy specific Style from one Element to Another using JS

To copy a specific 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 example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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>
The code for this article is available on GitHub

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;
The code for this article is available on GitHub

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

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

# Copy all Attributes from one Element to Another using JS

To copy all attributes from one element to another:

  1. Convert the source's attributes to an array using the Array.from() method.
  2. Use the forEach() method to iterate over the array.
  3. Use the setAttribute() method to set each attribute on the target element.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style=" background-color: salmon; color: white; width: 150px; height: 150px; margin: 10px; " title="box" > Box content </div> <div id="another">Another Box</div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
function copyAttributes(source, target) { return Array.from(source.attributes).forEach(attribute => { target.setAttribute( attribute.nodeName === 'id' ? 'data-id' : attribute.nodeName, attribute.nodeValue, ); }); } const box = document.getElementById('box'); const another = document.getElementById('another'); copyAttributes(box, another);
The code for this article is available on GitHub

We created a reusable function that copies all the attributes from one element to another.

The Element.attributes() property returns a Map of strings representing the element's attributes.

index.js
const box = document.getElementById('box'); console.log(box.attributes); // ๐Ÿ‘‰๏ธ {0: id, 1: style, 2: title}

We used the Array.from() method to get an array containing the attribute names.

index.js
const box = document.getElementById('box'); // ๐Ÿ‘‡๏ธ [id, style, title] console.log(Array.from(box.attributes));

The function we passed to the forEach() method gets called with each element (attribute name) in the array.

On each iteration, we check if the attribute name is not equal to id before assigning it to the target element.

The values of the id attribute have to be unique on the page, so it wouldn't make sense to copy the id over.

We used a ternary operator to check if the attribute's name is equal to id.

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.

The nodeName property returns the qualified name of the attribute.

The nodeValue property returns the value of the attribute.

We used the setAttribute() method to set each attribute on the target element.

The setAttribute method takes 2 parameters:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.
If the attribute already exists on the element, the value is updated, otherwise, a new attribute is added with the specified name and value.

If I load the code from the example in my browser, I can see that the attributes have been copied over to the target element successfully.

Attributes copied over

Notice that the id of the element remains the same, it hasn't been copied over.

And the elements now look identical.

elements look identical

However, this wouldn't be the case if the source element has styles that are applied to it with an external style sheet.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev