So i have the following code
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
document.styleSheets[0].cssRules[0].style.color="blue";
</script>
</head>
//etc.
So basically this code works in IE and Mozilla, but not in Chrome. Actually, when you run document.styleSheets[0].cssRules
it returns an CSSRulesList Object(in IE and Mozilla), but in Chrome it returns null. Btw, for embedded styles this object seems to work even in Chrome.
So is this feature actually not available in Chrome? If so, is there a Chrome alternative that enables you to work with external style sheets/files using Javascript?
The alternative
This snippet could be helpful to see which collection is supported. It is recommended to use the
cssRules
collection first and if it is not supported, then use therules
collection.EDIT
The snippet below works as expected on IE8, IE11, Firefox, Chrome, Safari and Opera; on my local and production server; it also works on jsbin; but it doesn't work on jsfiddle - on any of the above browser!
If I change the
style
section to thisthe snippet above works only on IE11. So, it seems to be a
cross-domain policy issue
since Firefox is sayingThe Same Origin Policy disallows reading the remote resource at http://external-server/styles.css. This can be fixed by moving the resource to the same domain or enabling CORS.
Maybe the following snippet could solve the issue
Well, the
@import tip
failed! But let's check the headers received from the external serverAs we can see, we have the styles but we can't access or change them. Chrome and Opera are saying
Firefox is saying the same but in more details
and finally, even IE11 has the same opinion :)
Well, at this moment there's one more thing to consider - a CORS request?! CORS is supported on IE 8+, Firefox 3.5+, Chrome 3+, Opera 12+, Safari 4+ ...
Access CSS hosted on external domain using CORS
That's it, it works! Just tested on IE8, IE11, Firefox, Chrome, Opera and Safari. But... only if the
Access-Control-Allow-Origin
is enabled on the web-server, otherwise you'll get an error like thisXMLHttpRequest cannot load http://external-domain/styles.css. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
On my server it wasn't enabled so I had to do it myself. This may be a problem if one is on shared hosting.
Off-topic:
How to enable Access-Control-Allow-Origin on ApacheFirst, enable the Apache Headers module
Restart Apache
Under the
Directory
section of your Apache config file add these linesor add them in a .htaccess file. The last two may be omitted. If you want to limit access to only someone, replace the "*" from the previous line to, let's say, "www.my-kitchen.com". Another restart of web-server and that's it.