How to copy a block on one page to another page while maintaining CSS styles?

Let's say I have two pages whose javascript can talk to each other through the return value of window.open () or window.opener. Pages can (and usually will) have completely different css rules.

I select an arbitrary node in the heirachy DOM of one page (for example, a div element). Now I paste it into another document in some arbitrary (but legal) place in the hierarchy.

Now I also want to create CSS rules that look similar on the new page. I prefer the minimum number of properties in css rules.

Can I do this by doing some kind of comparison of styles and computed styles on the DOM elements of both documents? Would it help me if I temporarily removed classes from elements or otherwise modified them so that I could get calculated styles on elements with default styles and compare with them?

+4
source share
1 answer

http://jsfiddle.net/1ruvsqw1/1/

var e = document.getElementsByClassName('test')[0],
    div = e.cloneNode(true),
    newStyles = getComputedStyle(e);
document.body.appendChild(div);
var existingStyles = getComputedStyle(div);
for (var i in existingStyles) {
    console.log(i, existingStyles[i]);
    if (newStyles[i] != existingStyles[i]) div.style[i] = newStyles[i];
}

Just copy calculated styles in a nested loop.

+4
source

All Articles