How to Copy All Styles and Attributes from One Element to Another in JavaScript
When you're dynamically creating elements, you often want to make a new element look and behave exactly like an existing one. This involves more than just copying its HTML content; you need to duplicate its visual appearance (CSS styles) and its HTML attributes (like class, title, or data-* attributes).
This guide will teach you the modern, standard methods for cloning an element's styles and attributes. You will learn the critical difference between copying inline and computed styles and see how to create a complete visual and structural duplicate of an element.
Step 1: Copying All Computed Styles
The most important part of duplicating an element's appearance is copying its styles. A common mistake is to only look at element.style, which only contains inline styles from the style="..." attribute. To get a true visual copy, you must copy the computed styles.
The logic:
- Use
window.getComputedStyle(sourceElement)to get an object containing the final, rendered values of all CSS properties from the source element. - This object's
cssTextproperty contains a string of all these styles. - Assign this string to the
targetElement.style.cssTextproperty.
For example, we have a source element with styles from both an external stylesheet and an inline attribute, and we want to copy all of them to a new element.
<head>
<style>
/* From a stylesheet */
.box { color: white; }
</style>
</head>
<body>
<div id="source" class="box" style="background-color: salmon;">
Source Box
</div>
<div id="target">Target Box</div>
</body>
Solution:
const source = document.getElementById('source');
const target = document.getElementById('target');
// Get the final, rendered styles of the source element.
const computedStyles = window.getComputedStyle(source);
// Apply these styles as inline styles on the target element.
target.style.cssText = computedStyles.cssText;
console.log(target.style.color); // Output: "rgb(255, 255, 255)"
console.log(target.style.backgroundColor); // Output: "salmon"
The cssText property provides a powerful one-liner for cloning the complete visual appearance of an element.
Step 2: Copying All HTML Attributes
In addition to styles, you'll often want to copy HTML attributes like class, title, or data-* attributes to ensure the new element behaves the same way.
The logic:
- Access the
sourceElement.attributesproperty, which is a collection of all the element's attributes. - Iterate over this collection.
- For each attribute, use
targetElement.setAttribute()to apply it to the target element.
This function encapsulates the attribute-copying logic.
function copyAttributes(source, target) {
for (const attr of source.attributes) {
target.setAttribute(attr.name, attr.value);
}
}
// Example Usage:
const source = document.getElementById('source');
const target = document.getElementById('target');
source.setAttribute('data-id', '123');
source.setAttribute('title', 'Source Box');
copyAttributes(source, target);
console.log(target.className); // Output: "box"
console.log(target.getAttribute('data-id')); // Output: "123"
This simple function copies all attributes, including id. If your target element needs a unique ID, you may want to add logic to skip or modify it.
Putting It Together: A Reusable cloneAppearance Function
By combining both of these steps, we can create a powerful utility function that makes one element a visual and structural clone of another.
The reusable function:
/**
* Copies all computed styles and HTML attributes from a source element to a target element.
* @param {HTMLElement} source The element to copy from.
* @param {HTMLElement} target The element to copy to.
*/
function cloneAppearance(source, target) {
// 1. Copy computed styles
const computedStyles = window.getComputedStyle(source);
target.style.cssText = computedStyles.cssText;
// 2. Copy attributes
for (const attr of source.attributes) {
// We skip the 'style' attribute because cssText handles it more completely.
// We also skip 'id' to avoid creating duplicate IDs.
if (attr.name !== 'style' && attr.name !== 'id') {
target.setAttribute(attr.name, attr.value);
}
}
}
Solution:
const source = document.getElementById('source');
const target = document.getElementById('target');
cloneAppearance(source, target);
After running this function, the target element will be a near-perfect visual and structural duplicate of the source element.
Conclusion
Cloning an element's appearance and attributes in JavaScript is a two-step process that requires understanding the difference between various DOM properties.
- To copy visual styles, you must use
window.getComputedStyle(source)to get the final, rendered styles. Then, apply them usingtarget.style.cssText. Relying onsource.stylealone is not enough, as it misses styles from stylesheets. - To copy HTML attributes, iterate over the
source.attributescollection and apply each one to the target usingtarget.setAttribute().
By combining these two techniques, you can reliably duplicate elements for dynamic UIs, testing, or any other DOM manipulation task.