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!

Answers


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;
    }
  } 
}

You should pass strings enclosed in quotes - otherwise JavaScript thinks they're variable names:

<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>

But your real problem is this:

a = document.getElementsByTagName("link")

sets a as an HTMLCollection object, not as the link itself. Change it to:

a = document.getElementsByTagName("link")[i]

And you'll be fine.

It seems alistapart isn't perfect after all.


Need Your Help

deep copy a list of user defined class

c# list inheritance copy

i have a list of class of below type

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.