Part 4. jQuery Basics: Selecting HTML elements using CSS classes

Published on: July 19, 2013 Written by: Thokozani Mhlongo

In our last post we touched on how to select HTML elements using pseudo selectors. We looked into how we can use some of CSS pseudos to our advantage and when would you need to use this technique to manipulate your web pages. This post will be short and everything will be based on one example. We are now going to dive deeper in selecting our HTML elements using our CSS classes. We'll also extend on this by adding, and removing CSS classes dynamically, so without wasting any time lets get straight to it.

Our Example

We will be making a traffic light for today. Yey! Should be fun right? Every 5 seconds we will be changing a background color of a div element by toggling between 3 CSS classes (Namely .green for go, .yellow for slow, and .red for stop). Sounds simple enough right? YES it is that simple. A basic implementation would be to check what kind of light we are currently at every 5 second interval and then change the CSS class. Now remember we will be using CSS classes to select our HTML elements. We will be starting from green to red and all the way back again The following does it all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xml:lang="en" lang="en">

    <title>Traffic light examoke</title>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
    <style type="text/css">
        .traffic-light {
            width: 40px;
            height: 40px;
            border: 1px solid #aaaaaa;

        .green { background: green; }
        .red { background: red; }
        .yellow { background: yellow; }
    <script type="text/javascript">
        $(document).ready(function() {
            var currentLight = 'green' //Initialize this variable with our .green css class
            setInterval(function() {
                //This function will execute every 5 seconds
                var newLight = '';
                if(currentLight == 'green') newLight = 'yellow';
                else if(currentLight == 'yellow') newLight = 'red';
                else if(currentLight == 'red') newLight = 'green';

                $('.' + currentLight).removeClass(currentLight); //This removes the old light state
                $('.traffic-light').addClass(newLight); //This adds the new light state

                //Its important to update the current light
                currentLight = newLight;
            } , 5000); //This sets the 5 second interval.
    <div class="traffic-light green"></div>

We first defined our traffic light styles that set the different backgrounds within our style tag. We set green as the default light when the page loads. We therefore set our variable "currentLight" to green, and it is this variable that will keep the state of the traffic light. As you may have noticed, we used a javascript function called setInterval( ) to simulate a countdown. This function accepts two parameters, first being the function to execute and second being the interval in milliseconds. In this function is where we toggle the CSS classes by checking the value of currentLight and determining the new light through if statements. Next are the two lines that do the switching of the CSS classes. The removeClass( ) method removes a class from an HTML element and addClass( ) adds a class. We therefore update the currentLight variable after changing the light. When selecting elements using CSS classes, a dot precedes the class name just like how you define them in your stylesheet. This is why we concatenate the the dot on the line:

$('.' + currentLight).removeClass(currentLight);    


In this tutorial we further discussed using CSS classes in selecting and manipulating our HTML elements. There is one more post on this basics series which will touch-base on generating HTML elements and changing content dynamically. On future posts we will start doing more complex things with jQuery, looking at widgets, and rolling your own plugins