Redefine a class’s styles

In this simple example we have a list of fruit and vegetables. Each item of fruit has been given a class of fruit and each vegetable a class of veg. We can use DOM scripting to effectively redefine the styles of each class.

I created a generic function to perform this:

function setClassStyle(tagName, className, styleName, styleValue) {
   elemColl = document.getElementsByTagName(tagName);
   for (var i = 0; i < elemColl.length; i++) {
      var elemClass = elemColl[i].className; 
      if (elemClass == className) {
          elemColl[i].style[styleName] = styleValue;
      }
   }
}

We are passing four parameters to the function:

  1. tagName = li
  2. className = fruit
  3. styleName = background
  4. styleValue = yellow

The function finds all the li elements with a class of fruit and sets the background to be yellow.

To accomplish this, the function starts off with the getElementsByTagName method. All elements and attributes on the page are held in nested arrays called HTMLCollections. getElementsByTagName('li') gives us an HTMLCollection of all the li elements in the document.

As HTMLCollections are arrays of objects, we can use a for loop to step through each element in the collection. For each li, we use the className property to find the class name; this we assign to the elemClass variable.

Next we check if the li has the same class we passed to the function. If it does we change the style accordingly. Note that square brackets are equivalent to using a full stop (.), as style properties are yet another array of an HTML object.

As it stands,the function applies to all elements in the document. Using the DOM tree, we can make the function apply only to items within a given list. By giving the ul an id of mylist we need only change the first line of the function, replacing document with the more specific document.getElementById:

elemColl = document.getElementById('mylist').getElementsByTagName(tagName);