Changing Stylesheets

Question: Hi, I am trying to take a file(could be a js or txt file) and from a drop down list change the value inside of the link tag.
Here is the tag:

<link href="/css/sunstone1.css" rel="stylesheet" type="text/css" media="screen" />

From the dropdown I want to only change the value of sunstone1.css to another value that comes from the dropdown. Can this be done?

Answer: You can't update that attribute directly. The easiest way to achieve what you want is to define alternate stylesheet links in the head of the page for all of the alternative stylesheets you want to have available and give them all titles.

<link href="/css/sunstone1.css" rel="stylesheet" type="text/css" title="sunstone1" media="screen" />
<link href="/css/sunstone2.css" rel="alternate stylesheet" type="text/css" title="sunstone2" media="screen" />
<link href="/css/sunstone3.css" rel="alternate stylesheet" type="text/css" title="sunstone3" media="screen" />

You can then use Javascript to switch which of the stylesheets is active.

function changeStyle(title) {
var lnks = document.getElementsByTagsName('link');
for (var i = lnks.length - 1; i >= 0; i--) {
if (lnks[i].getAttribute('rel').indexOf('style')> -1 && lnks[i].getAttribute('title')) {
lnks[i].disabled = true;
if (lnks[i].getAttribute('title') == title) lnks[i].disabled = false;

Now simply call that function specifying the title of the stylesheet that should be active eg. changeStyle('sunstone2');


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow