Last updated: Mar 5, 2024
Reading timeยท5 min
To copy all styles from one element to another:
document.createElement()
method.cssText
on the newly created element.Here is the HTML for the examples.
<!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>
And here is the related JavaScript code.
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);
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.
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.
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.
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.
And the elements look identical in my browser.
To copy a specific 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 example.
<!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>
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;
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.
To copy all attributes from one element to another:
Array.from()
method.forEach()
method to iterate over the array.setAttribute()
method to set each attribute on the target element.Here is the HTML for the example.
<!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>
And here is the related JavaScript code.
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);
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.
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.
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.
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:
name
- the name of the attribute whose value is to be set.value
- the value to assign to the attribute.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.
Notice that the id
of the element remains the same, it hasn't been copied
over.
And the elements now 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.
You can learn more about the related topics by checking out the following tutorials: