I'm trying to clone a <div>
in an <iframe>
, and append the cloned div to the parent DOM. I keep the div as display: none
to start (when in the iframe), and I make it visible when I clone it in the parent. This all works fine, and here's a minimal snippet:
The parent (top.html):
<iframe src=foo.html></iframe>
The iframe (foo.html)
<html>
<HEAD>
<style>
#myid {
display: none;
}
</style>
</HEAD>
<body onload="onload()">
<script>
function onload() {
var div = document.getElementById("myid");
var newdiv = div.cloneNode(true);
var body = parent.document.getElementsByTagName("body")[0];
newdiv.id = "new" + div.id;
newdiv.style.display = "block";
newdiv.style.position = "absolute";
newdiv.style.top = "100px";
newdiv.style.left = "100px";
newdiv.style.width = "100px";
newdiv.style.height = "100px";
newdiv.style.background = "red";
body.appendChild(newdiv);
};
</script>
<div id=myid>
<p>foo
</div>
</body></html>
My issue that I would like to use internal css to define #myid
WHEN THE DIV IS CLONED INTO THE PARENT. But, once the the div is cloned, it only references the CSS in the parent... I'm not (readily) able to modify the CSS of the parent.
Can I make the internal CSS "stick" to the div when it gets cloned?
For example, if I delete the line above:
newdiv.style.background = "red";
And instead add to the internal CSS:
background: red;
The red doesn't stay once I clone the div to the parent.
My only other solution is to just do it all inline, by changing the div, like:
<div id=myid style="background: red;">
And that works, its just that I have a lot of CSS and it's a mess to maintain that way.
My solution to this (from @charlietfl's suggestion) was to add:
newdiv.style.cssText = window.getComputedStyle(div).cssText;
to copy the computed CSS to the cloned div. Now I can add background: red
to the internal CSS, and it is "stuck" to the clone.
The final solution is below:
<html>
<HEAD>
<style>
#myid {
/* Added style here */
background: red;
display: none;
}
</style>
</HEAD>
<body onload="onload()">
<script>
function onload() {
var div = document.getElementById("myid");
var newdiv = div.cloneNode(true);
var body = parent.document.getElementsByTagName("body")[0];
/* Copy styles here */
newdiv.style.cssText = window.getComputedStyle(div).cssText;
newdiv.id = "new" + div.id;
newdiv.style.display = "block";
newdiv.style.position = "absolute";
newdiv.style.top = "100px";
newdiv.style.left = "100px";
newdiv.style.width = "100px";
newdiv.style.height = "100px";
body.appendChild(newdiv);
};
</script>
<div id=myid>
<p>foo
</div>
</body></html>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments