Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getElementsByClassName in javascript-function? [duplicate]

I can't figure out how to use multiple IDs in JavaScript. No problem with single ID and getElementById, but as soon as I change IDs to class and try using getElementsByClassName the function stops working. I've read about a 100 post about the topic; still haven't found the answer, so I hope someone here knows how to make getElementsByClassName work.

Here's some simple code that I have used for testing:

function change(){
    document.getElementById('box_one').style.backgroundColor = "blue";
}

function change_boxes(){
    document.getElementsByClassName ('boxes').style.backgroundColor = "green";
}

   
<input name="" type="button" onClick="change(document.getElementById('box_one')); change_boxes(document.getElementsByClassName('boxes'))" value="Click" />   

<div id="box_one"></div>
<div class="boxes" ></div>
<div class="boxes" ></div>
like image 209
jan199674 Avatar asked Jan 03 '13 16:01

jan199674


People also ask

What does getElementsByClassName () do in JavaScript?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.

Does getElementsByClassName return NodeList?

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

Does getElementsByClassName return in order?

getElementsByClassName("a") will reliably list them in order: d1, d2, d3, d4, d5.

What is the difference between getElementById and getElementsByClassName?

getElementById() is used to access the DOM elements using their id and getElementsByClassName() is used to access element(s) using their class .


2 Answers

getElementsByClassName() returns a nodeList HTMLCollection*. You are trying to operate directly on the result; you need to iterate through the results.

function change_boxes() {
    var boxes = document.getElementsByClassName('boxes'),
        i = boxes.length;

    while(i--) {
        boxes[i].style.backgroundColor = "green";
    }
}

* updated to reflect change in interface

like image 127
Mathletics Avatar answered Sep 30 '22 19:09

Mathletics


getElementsByClassName Returns a set of elements which have all the given class names

var elements = document.getElementsByClassName('boxes');
for(var i=0, l=elements.length; i<l; i++){
 elements[i].style.backgroundColor = "green";
}
like image 34
Scipion Avatar answered Sep 30 '22 18:09

Scipion