Sabre Sabre - 6 months ago 20
Javascript Question

How to apply css to an iframe

I have an iframe which i want to appy a css file to it. I have tried some examples of the internet but haven't been successful.

Below is my code

<?php
include( 'site/simple_html_dom.php');
$html = file_get_html('http://roosterteeth.com/home.php');
foreach ($html->find('div.streamIndividual') as $div)
{
file_put_contents('site/test.htm', $div, FILE_APPEND | LOCK_EX);
}
?>
</head>
<body>
<iframe src="site/test.htm" style="width:480px; height:800px;"
scrolling=true></iframe>
</body>


Below is the jquery script I have tried

$('document').ready(function() {
var cssLink = document.createElement("site/test.htm")
cssLink.href = "style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['frame1'].document.body.appendChild("site/stylesheet.css");
});


Im not sure if the jquery code is wrong. All of the files are in the same domain. I hope you can help and thank you for your time.

Answer

Your js-code is not to bad, but there are some syntax-errors (press F12 to enter the console and to view the errorconsole). More important is, that you want your element to be a link element and you want to append it to the head of your iframe:

$('document').ready(function() {
  var cssLink = document.createElement("style"); 
  cssLink.href = "style.css"; 
  cssLink.rel = "stylesheet"; 
  cssLink.type = "text/css"; 
  frames[0].document.head.appendChild(cssLink);
});
Comments