23

Possible Duplicate:
Change an element's CSS class with JavaScript

I'm trying to set div's attributes with this script. And i have problem in third line, where I'm trying to get div-s from parent div which id is "loading". but here the problem, it seems like there in variable divs is nothing. why's that?

Script:

function  blink() {
    document.getElementById("loading").setAttribute("class","loader");
    var divs = document.getElementById("loading").getElementsByTagName("div");
    alert(divs[0].class);
    for(var i=0;i<divs.length;i++) {
        var _id = divs[i].id;
        document.getElementById(divs[i].id).setAttribute("class", "bar");
    }       
}

html:

<div id="loading" class="loader2">
<a href="#" onClick="blink()">
    <div class="bar_"></div>
    <div class="bar_"></div>
    <div class="bar_"></div></a>
</div>

I want to replace divs class: "bar_" to "bar". that's what I'm trying to do.

Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
anonf34
  • 313
  • 1
  • 3
  • 8

2 Answers2

31
  • class is a future reserved word in JavaScript. Use className, not class.
  • As a general rule, use properties, not setAttribute
  • There's no need to re-get the <div> by ID when you already have them in divs!

So:

function blink() {
    var loader = document.getElementById("loading");
    loader.className = "loader";
    var divs = loader.getElementsByTagName("div");

    for(var i=0; i<divs.length; i++) {
        divs[i].className = "bar";
    }
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

Putting a div inside an a tag is not valid html, which doesn't help. But the main problems are that to read the class attribute you need to use el.className. Also, you're trying to read the id attribute for your inner divs when you haven't defined it in the html.

wheresrhys
  • 22,558
  • 19
  • 94
  • 162