Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

Append CSS to iframe

I want to be able to change the CSS used in an iframe from a link.

My iframe does not have a name, only an id.

My code below does NOT work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
<script type="text/javascript">
function addEditorCSS (child,css) {
  var ifr = getElementById(child);
  var headID = ifr.document.getElementsByTagName("head")[0];
  var cssNode = ifr.document.createElement("link");
  cssNode.type = "text/css";
  cssNode.rel = "stylesheet";
  cssNode.href = css;
  cssNode.media = "screen";
  headID.appendChild(cssNode);
}
</script>
</head>
<body>
<h1>Hello World</h1>
<iframe src="2.html" id="elm1_ifr"></iframe>
<hr />
<a href="javascript:('elm1_ifr','http://fds2432.googlepages.com/red.css')">Change CSS</a>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of quincydude
quincydude
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Michel Plungjan
FF and IE
Note I change ID to NAME and fixed the href of the clicked link

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
<script type="text/javascript">
function addEditorCSS (child,css) {
  var ifr = window.frames[child];
  var headID = ifr.document.getElementsByTagName("head")[0];
  var cssNode = ifr.document.createElement("link");
  cssNode.type = "text/css";
  cssNode.rel = "stylesheet";
  cssNode.href = css;
  cssNode.media = "screen";
  headID.appendChild(cssNode);
}
</script>
</head>
<body>
<h1>Hello World</h1>
<iframe src="2.html" name="elm1_ifr"></iframe>
<hr />
<a href="#" onClick="addEditorCSS('elm1_ifr','http://fds2432.googlepages.com/red.css'); return false">Change CSS</a>
</body>
</html>

Open in new window

Avatar of hankknight

ASKER

Thanks!

mplungjan, your code will not work for me because as I mentioned in the question, my iframe does NOT have a name, only an id.

quincydude, your code works great.
var ifr = window.frames[0];

will work for a nameless frame where 0 is the first frame and subsequent frames are numbered 1 and up
but the solution given works in IE and FF
I have run into trouble implamenting this concept into TinyMCE.

I have asked a related question here:
https://www.experts-exchange.com/questions/24249167/Append-CSS-to-TinyMCE-iframe.html