Jason Chen
Jason Chen

Reputation: 2577

How do I use getclassbyelemenentnames?

So currently I have this bit of code:

function bgchanger(color){
  document.getElementById("headwrapper").style.backgroundColor = color;
  document.getElementById("footerwrapper").style.backgroundColor = color;
}

Accompanied by this HTML:

<div id="blue" style="cursor: pointer" onClick="bgchanger('blue')"></div>

It works well for changing the color of divs on click. However, it's notably inefficient. Rather than identifying two divs by Element Id, I should be calling them by a shared class. But I'm a little unclear on exactly how I would arrange a document.getElementsByClassName since it's apparently arranged differently than the ID method.

Upvotes: 0

Views: 35

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

I assume you mean inefficient to code, since at runtime getElementById() will be fast. But as you imply, your JS would be neater if it could do this sort of thing by class rather than having a bunch of hard-coded ids. Indeed if your JS no longer needs to use ids you can omit them from your html too (unless they're used in your stylesheet).

So, getElementsByClassName() returns a list, so just loop through it:

function bgchanger(color){
    var list = document.getElementsByClassName("someClass");
    for (var i = 0; i < list.length; i++) {
        list[i].style.backgroundColor = color;
    }
}

Demo: http://jsfiddle.net/KNxBV/

Update with cookie monster's suggestion:

You can use querySelectorAll() instead of getElementsByClassName() - it has slightly better browser support:

    var list = document.querySelectorAll(".someClass");
    // other code as above. Note the . ---^

Updated demo: Demo: http://jsfiddle.net/KNxBV/1/

Upvotes: 2

Related Questions