16

I'm trying to use

 onmouseover="document.getElementsByClassName().style.background='color'"

to change the color of all divs with a given classname to another color when hovering over another page element.

Here is a jsfiddle -if anyone could give a few helpful pointers as to where I'm going wrong that would be great, I'm sure it's something really obvious that I'm missing. It worked with document.getElementById, but that only changed the color of the first div, not all of them.

Thanks :)

  • The post seems to have ommitted my greeting and won't let me edit it in :O –  Sep 20 '13 at 22:57
  • http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts/93989#93989 – PSL Sep 21 '13 at 03:32

1 Answers1

33

As the function name suggests getElementsByClassName returns a collection not just one object. So you need to loop through them and apply the color to it.

document.getElementsByClassName()
                   ^_______

Plus your id part is invalid. Id cannot have spaces and also it shouldn't appear again on the page which is violated by:

<th id="colorswitcher A" onmouseover="document.getElementsByClassName('a').style.background='red'">a</th>
<th id="colorswitcher B" onmouseover="document.getElementsByClassName('a').style.background='blue'">b</th>

You can do it this way (You can look up what is a handler and try play yourself with it.), don't use inline attributes for handlers.

window.onload=function(){
    var aColl = document.getElementsByClassName('a'); //Cache the collection here, so that even a new element added with the same class later we can avoid querying this again by using the cached collection.
    var bColl = document.getElementsByClassName('b');

    document.getElementById('A').addEventListener('mouseover', function(){
        changeColor(aColl, 'red');
    });

    document.getElementById('B').addEventListener('mouseover', function(){
        changeColor(bColl, 'blue');
    });
}
function changeColor(coll, color){

    for(var i=0, len=coll.length; i<len; i++)
    {
        coll[i].style["background-color"] = color;
    }
}

Fiddle

If you are really trying to do it for some real work, then don't change the style attribute, instead define classes and add/remove classes on mouseover, mouseout events so that you get the power of css' cascading property.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
PSL
  • 123,204
  • 21
  • 253
  • 243
  • Hi, thanks for the answer! I'm a bit of a noob, how would I go about looping through them? *edit: fixed IDs. thanks. –  Sep 20 '13 at 22:58
  • 1
    Might be important to mention that `getElementsByClassName` returns a live collection, and that's why you can "cache" `aColl` and `bColl` at the top of your function (otherwise, you'd have to re-query in the event handlers). Either way, great answer. – Ian Sep 20 '13 at 23:34
  • @lan yeah. great point to add. – PSL Sep 20 '13 at 23:40