3

I am having some trouble using Javascript to change the class of a div element. The method I am currently using (See code below) works in Chrome and Firefox but not IE8 (I haven't tested IE9 but assume it either works already or will once ie8 does).

The curious part is that in ie8 when I am changing the class of an input element, it works. but changing the class of a div does nothing (class isn't changed at all)

JavaScript

function switchTab(tab, button) {
    var divs = document.getElementsByName("tab-content");
    var d;
    for (counter=0; counter<divs.length; counter++) {
      d = divs[counter];
      if (d.id == tab)
        d.className = "members";
      else
        d.className = "members-hidden";
    }
    var buttons = document.getElementsByName("button");
    var bu;
    for (counter=0; counter<buttons.length; counter++) {
      bu = buttons[counter];
      if (bu.id == button)
        bu.className = "tab-active";
      else
        bu.className = "tab";
    }
    return false;

}

Relevant HTML Snippets

<div id="nav">
<ul class="membernav">
   <li><input id="ob" type="button" class="tab-active" name="button" onclick="return switchTab('officers', 'ob')" value="Officers"></li>
   <li><input id="pb" type="button" class="tab" name="button" onclick="return switchTab('partners', 'pb')" value="Partners"></li>
   <li><input id="mb" type="button" class="tab" name="button" onclick="return switchTab('managers', 'mb')" value="Managers"></li>
   <li><input id="ab" type="button" class="tab" name="button" onclick="return switchTab('associates', 'ab')" value="Associates"></li>
</ul>
</div>

and further down in HTML

<div id="tab-contents">
<div class="members" name="tab-content" id="officers">
   <!-- irrelevant content removed to save space -->
</div>

<div class="members-hidden" name="tab-content" id="partners">
  <!-- irrelevant content removed to save space -->
</div>

<div class="members-hidden" name="tab-content" id="managers">
   <!-- irrelevant content removed to save space -->
</div>

<div class="members-hidden" name="tab-content" id="associates">
   <!-- irrelevant content removed to save space -->
</div>
</div>

The classes on the buttons are successfully being switched to/from tab and tab-active.

but the divs aren't being changed from members to/from members-hidden.

Have I made some silly mistake? because I change both the same way, why is one working and the other broken?

Ross Larson
  • 2,357
  • 2
  • 27
  • 38

1 Answers1

3

This post answers your question: getElementsByName in IE7

To summarize: IE does not support getting elements by name that do not support the name attribute by default. This is why your standard form input fields will work, but a div will not.

Community
  • 1
  • 1
Spicy Koala
  • 557
  • 3
  • 9