getElementsByClassName

getElementById had always been a nice way to reference attributes of an element in your html via javascript, but now with the dawn of HTML 5 you can update whole groups with the getElementsByClassName function which will collect all elements with the chosen class in an array for you to loop through and apply attributes to, or animate, or whatever.

For example, if I want to loop through my page for all items with the class name “red” and change the background color of these items to red, i would simply do the following:


var redItems = document.getElementsByClassName("red");
for (var i = 0; i < redItems.length; i++)
{
var redItem = redItems[i];
redItem.style.backgroundColor = "#FF0000";
}

note: be sure to put this code at the bottom of your web page, otherwise the items with this class will not have rendered and it will not find them.

Leave a Reply

Your email address will not be published. Required fields are marked *