How do I copy CSS style from one element to a new element in a separate document (an IFRAME for instance)?
I've tried to do so by using bobince's answer at JavaScript & copy style.
Please see my attempt below.
Thank you
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>copy CSS</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<style type='text/css'>
.myClass p {font-size:20px;color:blue;}
</style>
<script type="text/javascript">
$(function () {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
$('.myClass').each(function(){
var to=iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
console.log(to);
var from=this;
//Option 1
to.style.cssText= from.style.cssText;
//Option 2
for (var i= from.style.length; i-->0;) {
var name= from.style[i];
to.style.setProperty(name,
from.style.getPropertyValue(name),
priority= from.style.getPropertyPriority(name)
);
}
});
});
});
</script>
</head>
<body>
<div class="myClass">
<p>Stuff!</p>
<img alt="an image" src="dropdown_arrow_blue.gif">
</div>
<div class="myClass">
<p>More stuff!</p>
</div>
</body>
</html>
EDIT. Technically, this should work, however, it seems overkill.
//Option 3
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
}
var arrStyle = document.getElementsByTagName("style");
for (var i = 0; i < arrStyle.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
}