Search code examples
javascriptformsstylesheet

JavaScript stylesheet switcher not working?


So I'm trying to have a stylesheet switcher option on my page, where the user can click a radio button and it changes which stylesheet is being applied, but it's not working for me.

Here's what's in my head tag:

<link href="stylesheet.css" type="text/css" rel="stylesheet" title="main">
<link href="stylesheet2.css" type="text/css" rel="alternate stylesheet" title="alt1">
<link href="stylesheet3.css" type="text/css" rel="alternate stylesheet" title="alt2">
<script language="javascript">

function setActiveStyleSheet(title) {
 var i, a, main;
 for(i=0; (a = document.getElementsByTagName("link")); i++) {
 if(a.getAttribute("rel").indexOf("style") != -1
    && a.getAttribute("title")) {
   a.disabled = true;
   if(a.getAttribute("title") == title) a.disabled = false;
    }
  } 
}
</script>

And here's the actual radio form:

<p><input type="radio" name="look" onClick="setActiveStyleSheet('main')" checked> Light & dark blue</p>
<p><input type="radio" name="look" onClick="setActiveStyleSheet('alt1')"> Black & white</p>
<p><input type="radio" name="look" onClick="setActiveStyleSheet('alt2')">Yellow & red</p>

Anyone mind telling me what I'm doing wrong? Thank you!


Solution

  • variable a is array of elements, you should access its elemnts by index (ie. a[i]) and not directly.also, the for loop condition should be i < a.length.

    function setActiveStyleSheet(title) {
     var i, a, main;
    a = document.getElementsByTagName("link");
     for(i=0; i< a.length ; i++) {
     if(a[i].getAttribute("rel").indexOf("style") != -1
        && a[i].getAttribute("title")) {
       a[i].disabled = true;
       if(a[i].getAttribute("title") == title) a[i].disabled = false;
        }
      } 
    }