FFBbodie
FFBbodie

Reputation: 111

How to select multiple elements

i have made a script where i can give a div a backgroundcolor by clicking on one of the td tag in the table. the problem is, i want to give more divs a color.

with getElementById() it can only select one div and not 2.

my CSS:

td {width:20px; height:20px;}
.result{width:200px; height:100px; margin:10px auto; background:green;}

my script:

function bgcolor(color){
        els = document.getElementByClassName('result');
        for(i in els){
            els[i].style.backgroundColor = color;
        }
    }

my HTML:

<table>
    <tr>
        <td style="background:red;" onclick="bgcolor('red')"></td><td style="background:blue;" onclick="bgcolor('blue')"></td>
    </tr>
    <tr>
        <td style="background:green;" onclick="bgcolor('green')"></td><td style="background:yellow;" onclick="bgcolor('yellow')"></td>
    </tr>
    <tr id="row">
        <td style="background:brown;" onclick="bgcolor('brown')"></td><td style="background:grey;" onclick="bgcolor('grey')"></td>
    </tr>
</table>
<div class="result"></div>

what have i done wrong?

Upvotes: 1

Views: 3588

Answers (3)

phron
phron

Reputation: 1845

you call getElementByClassName(classname) which return the first element with the specified class, if you want all the elements you have to do document.getElementsByClassName(classname) (elements is plural)

Upvotes: 0

Vipin
Vipin

Reputation: 153

first of all use document.getElementsByClassName.

Upvotes: 0

George
George

Reputation: 36784

Create one function to change the color, use the parameter to specify which color. getElementsByClassName returns a collection, so you'll need to loop through the collection and apply the background color each time:

function bgcolor(color){
  els = document.getElementsByClassName('result');
  for(i in els){
    els[i].style.backgroundColor = color
  }
}

Then call it with

bgcolor('red');

Upvotes: 3

Related Questions