How to select elements with jQuery

In this tutorial I will demonstrate how to use the jQuery JavaScript framework to find and work with HTML DOM elements on a web page. If you would like to skip the reading and get a complete working example you can view it here.

Using jQuery To Select Elements

Perhaps the most fundamental and commonly used function of the jQuery framework is targeting one or more HTML elements on a web page with “selectors”. There are two basic selectors you should familiarize yourself with before doing anything else with jQuery; the “ID” selector and the “Class selector”. These two are written the same way as if you were referencing elements with CSS.

Simply place a dot in front of the class name to reference, or select, it. Let’s make a simple web page to demonstrate. We will create a few tags with a “red” class. When a button is clicked we’ll use jQuery to access those elements and set the CSS styles on them.

Let’s Look At Some Examples

To illustrate the use of the ID and Class selectors let’s create a simple HTML snippet.

<div class="container">
    <span id="blue">Blue ID</span><br />
    <span class="red">Red Class</span><br />
    <div class="container">
        <p>Paragraph with no styling</p>
        <p class="red">Paragraph with a class</p>
    </div>
</div>

On a web page it would look like this:

Modify element colors using jQuery; before shot

We have a variety of elements with some different Classes and ID’s. We will use the jQuery selectors to pick out those elements we want and modify their styles.

Changing Elements With jQuery

Using the HTML snippet above and access some of the nodes. We will create two jQuery variables; one referencing all elements with an “id” attribute of “blue”, and all elements with a “class” attribute of “red”. We will use the ID selector to search and find the first element, and we’ll use the Class selector to find the second set of elements.

Selecting Elements By The ID Attribute

Let’s start with the ID selector. IDs are indicated with the “#” sign. To find all elements with an ID equaling “blue” we would do this:

// Make a new jQuery object that represents the "blue" span element.
var $blue = $("#blue");
// Note: It is not necessary to name your variable with a $ at the beginning, but I like to do that so I remember that it's a jQuery object.
// This works fine too:
var blue = $("#blue");

jQuery objects contain many methods for working with the DOM. Since there is only one element in our snippet with an ID of “blue” the $blue variable we created will only refer to one element. If you were to inspect the value of the $blue variable you would see several methods as well as an array with one element.

Selecting Elements By The Class Attribute

Now let’s get all the elements with a class value of “red”. Classes are indicated with the “.” character.

// Make a new jQuery object that represents both "red" class elements.
var $red = $(".red");

The $red jQuery object will keep track of two elements; a “span” and a “p”. If you were to inspect the $red object you would see two elements in its array, along with all the regular jQuery methods. Now let’s change the colors on these three elements.

Manipulating Elements With jQuery

One way to change the color of our elements is using a jQuery function called “css”. The “css” function can be used to read or write. We will look at both.

// When "css" is passed one parameter (the style name) it will return a string with the value of that style.  We haven't set the "color" style on our elements so the following code will return empty strings.
$("#blue").css("color");
$(".red").css("color");
 
// We set the value of the color style by passing in two parameters (the style name, and the value).  If the style has not been set yet jQuery will add it.  If it already exists jQuery uses the existing style.  The following code will add a "color" style to the elements since one does not exist already.
$("#blue").css("color", "blue");
$(".red").css("color", "red");
 
// If we read the color styles again we will see that they now have the colors "blue" and "red" respectively.
$("#blue").css("color"); // returns "blue"
$(".red").css("color"); // returns "red"

On a web page it would look like this:
Modify element colors using jQuery; after shot

If we were to inspect the complete HTML snippet now, it would look like this:

<div class="container">
    <span id="blue" style="color:blue;">Blue ID</span><br />
    <span class="red" style="color:red;">Red Class</span><br />
    <div class="container">
        <p>Paragraph with no styling</p>
        <p class="red" style="color:red;">Paragraph with a class</p>
    </div>
</div>

A Complete Example

By now you should see how jQuery can be useful and easy in referencing and working with elements in the DOM. Below you can try a complete working example for yourself.

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
 
            // wait for everything to load before running any other JavaScript
            $(document).ready(function(){
 
                // handle the click event for the button
                $('#changeColorsButton').click(function(){
 
                    // When "css" is passed one parameter (the style name) it will return a string with the value of that style.
                    // We haven't set the "color" style on our elements so the following code will return black or empty strings.
                    alert($("#blue").css("color")); // returns an empty string
                    alert($(".red").css("color")); // returns an empty string
 
                    // We set the value of the color style by passing in two parameters (the style name, and the value).
                    // If the style has not been set yet jQuery will add it.
                    // If it already exists jQuery uses the existing style.
                    // The following code will add a "color" style to the elements since one does not exist already.
                    $("#blue").css("color", "blue");
                    $(".red").css("color", "red");
 
                    // If we read the color styles again we will see that they now have the colors "blue" and "red" respectively.
                    alert($("#blue").css("color")); // returns "blue"
                    alert($(".red").css("color")); // returns "red"
 
                    // return false so the web page doesn't refresh
                    return false;
 
                });
            });
        </script>
    </head>
    <body>
        <button id="changeColorsButton">Change Colors</button>
        <div class="container">
            <span id="blue">Blue ID</span><br />
            <span class="red">Red Class</span><br />
            <div class="container">
                <p>Paragraph with no styling</p>
                <p class="red">Paragraph with a class</p>
            </div>
        </div>
    </body>
</html>