Duplicating an element (and its style) with JavaScript

Viewed 36035

For a JavaScript library I'm implementing, I need to clone an element which has exactly the same applied style than the original one. Although I've gained a rather decent knowledge of JavaScript, as a programming language, while developing it, I'm still a DOM scripting newbie, so any advice about how this can be achieved would be extremely helpful (and it has to be done without using any other JavaScript library).

Thank you very much in advance.

Edit: cloneNode(true) does not clone the computed style of the element. Let's say you have the following HTML:

<body>
  <p id="origin">This is the first paragraph.</p>
  <div id="destination">
    <p>The cloned paragraph is below:</p>
  </div>
</body>

And some style like:

body > p {
  font-size: 1.4em;
  font-family: Georgia;
  padding: 2em;
  background: rgb(165, 177, 33);
  color: rgb(66, 52, 49);
}

If you just clone the element, using something like:

var element = document.getElementById('origin');
var copy = element.cloneNode(true);
var destination = document.getElementById('destination');
destination.appendChild(copy);

Styles are not cloned.

3 Answers

None of those worked for me, but I came up with this based on Luigi's answer.

copyStyles(source: HTMLElement, destination: HTMLElement) {

    // Get a list of all the source and destination elements
    const srcElements = <HTMLCollectionOf<HTMLElement>>source.getElementsByTagName('*');
    const dstElements = <HTMLCollectionOf<HTMLElement>>destination.getElementsByTagName('*');

    // For each element
    for (let i = srcElements.length; i--;) {
        const srcElement = srcElements[i];
        const dstElement = dstElements[i];
        const sourceElementStyles = document.defaultView.getComputedStyle(srcElement, '');
        const styleAttributeKeyNumbers = Object.keys(sourceElementStyles);

        // Copy the attribute
        for (let j = 0; j < styleAttributeKeyNumbers.length; j++) {
            const attributeKeyNumber = styleAttributeKeyNumbers[j];
            const attributeKey: string = sourceElementStyles[attributeKeyNumber];
            dstElement.style[attributeKey] = sourceElementStyles[attributeKey];
        }
    }
}
Related