The alternative
document.styleSheets[0].rules[0].style.color = "blue";
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 the rules
collection.
if (document.styleSheets[0].cssRules)
document.styleSheets[0].cssRules[0].style.color = "blue";
else if (document.styleSheets[0].rules)
document.styleSheets[0].rules[0].style.color = "blue";
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!
<!DOCTYPE>
<html>
<head>
<style type="text/css">
.panel {
background-color: #00ff00;
color: #ffffff;
width: 100px;
height: 100px;
font-size: 30px;
}
</style>
<script type="text/javascript">
window.onload = function(){
document.getElementById('button').onclick = function() {
if (document.styleSheets[0].cssRules)
document.styleSheets[0].cssRules[0].style.color = "black";
else if (document.styleSheets[0].rules)
document.styleSheets[0].rules[0].style.color = "black";
};
};
</script>
</head>
<body>
<div class="panel"><b>Text</b></div>
<input type="button" name="button" id="button" value="Change Color" />
</body>
</html>
If I change the style
section to this
<link rel="stylesheet" type="text/css" href="http://external-server/styles.css" />
the snippet above works only on IE11. So, it seems to be a cross-domain policy issue
since Firefox is saying The 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
<style type="text/css">
@import url("http://external-domain/styles.css");
</style>
Well, the @import tip
failed! But let's check the headers received from the external server
Remote Address: x.x.x.x:x
Request URL: http://www.external-domain.com/styles.css
Request Method: GET
Status Code: 200 OK
+[Request Headers] 10
-[Response Headers] 11
Accept-Ranges: bytes
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 105
Content-Type: text/css
...
As we can see, we have the styles but we can't access or change them. Chrome and Opera are saying
`Uncaught TypeError: Cannot set property 'color' of undefined`;
Firefox is saying the same but in more details
`TypeError: document.styleSheets[0].cssRules[0].style is undefined`
and finally, even IE11 has the same opinion :)
`SCRIPT5007: Unable to set property 'color' of undefined or null reference.
File: css.html, Line: 30, Column: 4`
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
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
// Access CSS hosted on external domain using CORS
// http://stackoverflow.com/users/1310701/hex494d49
//
window.onload = function(){
var xhr = CORSRequest("GET", "http://external-domain/styles.css");
if (!xhr){ // if CORS isn't supported
alert("Still using Lynx?");
return;
}
xhr.onload = function() {
var response = xhr.responseText;
appendCSS(response);
}
xhr.onerror = function() {
alert('Something went wrong!');
};
xhr.send();
document.getElementById('button').onclick = function() {
if (document.styleSheets[0].cssRules)
document.styleSheets[0].cssRules[0].style.color = "black";
else if (document.styleSheets[0].rules)
document.styleSheets[0].rules[0].style.color = "black";
};
};
var appendCSS = function(css){
var s = document.createElement('STYLE');
s.setAttribute('type', 'text/css');
if(s.styleSheet) // IE
s.styleSheet.cssText = css;
else // the rest of the world
s.appendChild(document.createTextNode(css));
document.getElementsByTagName('HEAD')[0].appendChild(s);
};
var CORSRequest = function(method, url){
var xhr = new XMLHttpRequest();
if("withCredentials" in xhr){ // Chrome, Firefox, Opera, Safari
xhr.open(method, url, true);
}else if(typeof XDomainRequest != "undefined"){ // IE
xhr = new XDomainRequest();
xhr.open(method, url);
}else{ // CORS isn't supported
xhr = null;
}
return xhr;
};
</script>
</head>
<body>
<div class="panel"><b>Text</b></div>
<input type="button" name="button" id="button" value="Change Color" />
</body>
</html>
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 this
XMLHttpRequest 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 Apache
First, enable the Apache Headers module
ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load
Restart Apache
/etc/init.d/apache2 restart
Under the Directory
section of your Apache config file add these lines
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
or 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.