Results 1 to 3 of 3

Thread: How do I change the class of multiple divs?

  1. #1
    Join Date
    Jun 2007
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question How do I change the class of multiple divs?

    How do I change the class of multiple divs at the same time using the "document.getElementsByTagName" function?
    It seems like I can do everything but change the class of the objects defined with the "document.getElementsByTagName" function; I can display an alert stating how many objects are in that function, how many have a certain class...
    but I cant seem to change the class!
    I am using the following javascript to try and change the class:


    Code:
    function divc2(){
    divi=document.getElementsByTagName('div');
    divi.className='class1';
    }
    function divc1(){
    divi=document.getElementsByTagName('div');
    divi.className='class2';
    }
    my stylesheet:

    Code:
    .class1{
    color:#000fff;
    }
    .class2{
    color:#5e5e5e;
    }
    and the body of my test page is:

    HTML Code:
    <div class="class1" id="div">Div1</div><div class="class1" id="div2">Div2</div>
    <a href="javascript:divc2()">Change To Class2</a> | <a href="javascript:divc1()">Change To Class1</a>
    Is there something wrong with this code? It seems to me like it should do the job, but it doesn't. I'm using the FireBug extension for FireFox and that doesn't come up with any errors, so why doesn't it work?

    (My Test Page Is Located At http://dev.formulationx.com/dlinkt/)

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    The object returned by getElementsByTagName() is a collection, not a single element. You can set arbitrary properties on any object in ECMAScript (hence the lack of an error), but setting the className on the collection doesn't do much: you need to iterate through its members and set each className individually.
    Code:
    function divc1(){
      var divs = document.getElementsByTagName('div');
      if(divs)
        for(var i = 0, e = divs[0], n = divs.length; i < n; e = divs[++i])
          e.className='class2';
    }
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. #3
    Join Date
    Jun 2007
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up Thanks

    Thanks, That script worked perfect!
    (I'm not that grate at javascript)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •