简体   繁体   中英

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?

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');

你调用getElementByClassName(classname)返回带有指定类的第一个元素 ,如果你想要你做的所有元素document.getElementsByClassName(classname) (元素是复数)

首先使用document.getElementsByClassName。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM