How to use jQuery selectors

Whether you’re new to jQuery or have been using it for a while, the chances are you might not be making full use of the selector syntax.

Rather than simply listing the possible selectors, in this tutorial we will work through a practical example in which we create an interactive page component, introducing the basics if you’re a beginner. After that we will run through some of the other selector options you can choose from.

Create a page

Create a new HTML5 page:

<!DOCTYPE html>
 <html>
 <head>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <script type="text/javascript">
</script>
<style type="text/css">
</style>
</head>
<body>
</body>
</html>

Notice the link to the current jQuery source — alter this if you intend to use your own copy. Add the following to the body section of the page:

<div id="grid">
</div>

Build page content in JavaScript

Since we are using JavaScript, let’s build some of the page elements in our script section. Start by checking that the document is ready:

$(document).ready(function(){
});

All of our JavaScript code will be placed inside this function. We are building a simple interactive element in which a grid of colored shapes will animate on user interaction with the mouse. The element will be ten shapes in width and height, with the colors reflecting a rainbow palette:

001

Begin by defining the number of rows/columns and the colors:

var numRows=10;
var colors = new Array("#a13143", "#b17941", "#aca135", "#9aa633", "#539a2f", "#2d946c", "#2d6994", "#2d3894", "#592d94", "#942d8b");

Add a loop inside which we will create the shapes:

var i;
for(i=0; i<numRows; i++) {
}

The loop will iterate once for each row/column. Inside the loop, create an element to represent each column in the grid, assigning it a class attribute:

var column = document.createElement("div");
column.setAttribute("class", "column");

Next add a second loop inside the first one to create the shapes within each “column”:

var j;
for(j=0; j<numRows; j++){
}

Inside this second loop, create an element for each shape, give it a class attribute using the loop index and append it to the “column” element:

var box = document.createElement("div");
box.setAttribute("class", "box col"+j);//class names "box col0", "box col1" etc
column.appendChild(box);

After the inner loop but still inside the first loop we added, append each column to the grid element we added to the body section:

$("#grid").append(column);//ID selector

Here is the first example of using a selector, in this case the ID attribute we included in HTML. The selector gives your code a reference to the element in question, which you can then call other jQuery methods on, as we do with the append method here. The loops will result in the following HTML code structure:

 <div id="grid">
 <div class="column">
 <div class="box col0"></div>
 <div class="box col1"></div>
 <div class="box col2"></div>
 <div class="box col3"></div>
 <div class="box col4"></div>
 <div class="box col5"></div>
 <div class="box col6"></div>
 <div class="box col7"></div>
 <div class="box col8"></div>
 <div class="box col9"></div>
 </div>
 <div class="column">
 <div class="box col0"></div>
 <div class="box col1"></div>
 <div class="box col2"></div>
 <!--and so on for 10 columns/rows...-->
</div>
</div>

Let’s demonstrate another selector to style the shapes. After the first loop you added, still inside the document ready function:

var c;
for(c=0; c<colors.length; c++) {
        $(".col"+c).css("background-color", colors[c]);//class plus suffix selector
}

We use the color array we created to set the background on each color class inside a loop. In this case the class name together with the array index. Each “box” element with “col0” class will have the color at 0 in the array, and so on. Now let’s add some CSS to our style section for both “column” and “box” elements:

div.column {
width:25px;
float:left;
}
div.box {
width:12px;
height:12px;
margin-left:5px;
margin-top:5px;
border-radius:5px;
}

Add interactivity

Each time the user rolls their mouse over a shape, it will slide to the right or left and change in opacity, also changing in color when it moves to the left. In the script section, still inside the document ready function, add a mouseenter listener to all div elements with “box” class:

$("div.box").mouseenter(function(){
});

This time the selector specifies the element type as well as class. When the user rolls their mouse over the shape and it moves to the right, we will add a class attribute of “right”. Inside the function, check whether the shape is currently on the right using this attribute, animating it to the left or right as appropriate:

if($(this).hasClass("right")){
        $(this).animate({marginLeft:'-=12px', opacity:'1.0'});
}
else {
        $(this).animate({marginLeft:'+=12px', opacity:'0.5'});
}
$(this).toggleClass("right");

Notice that we use the this selector here, which is possible because we are inside an event listener function for the element. The this refers to whatever “box” element the user has rolled their mouse over. The animate method specifies a CSS property to animate, indicating a pixel value to add to the left margin, with a negative value moving the shape to the left and a positive value moving it to the right. The last line here toggles the class on and off so that the shapes will move back and forth, decreasing in opacity when they move to the right.

Let’s complicate things a little by using our color array to alter the color of each shape whenever it moves back to the left. Add the following to the if section of the above code, after the “$(this).animate” line:

//get full class attribute of shape being rolled over
var fullClass = $(this).attr("class");
//get color part e.g. "col0" then retrieve integer suffix
var colorNum = parseInt(fullClass.substr((fullClass.indexOf("col")+3), 1));
//work out new color number
var newColor;
if(colorNum==(colors.length-1)){
    newColor=0;//reached end of color array - reset to zero
}
else
{
   newColor=colorNum+1;//increment number to use next color in array
    //set the background using color array
    $(this).css("background-color", colors[newColor]);
    //remove existing color class
    $(this).removeClass("col"+colorNum);
    //add new color class
    $(this).addClass("col"+newColor);
}

Remember that each “box” element has a class attribute representing its color: “col0”, “col1” and so on. Each shape will iterate through the color array if the user continues to roll over it as the integer in this attribute increments.

002

Before we leave the grid, let’s randomly make one “box” in each “column” square to try out another selector. After the mouseenter function:

var r;
for(r=0; r<numRows; r++){
        //choose a random box from the ten in column r
        var randBox = Math.floor(Math.random() * numRows) + (r*numRows);
        $(".box:eq("+randBox+")").css("border-radius", "0");//box at random number position
}

Here we use the eq selector to select the nth element. In this case we select a “box” element in each “column” using a random number function. The following code would select the 8th “box” in the document:

$(".box:eq(7)")

The first “box” element in the page is at index 0 and the last is 99.

003

If, for example, you wanted to select every first “box” element that is a direct child of a “column” you could use the following:

//the > ensures the element is a direct child of the specified parent
$(".column > .box:nth-child(1)").css("border-radius", "0");//nth-child indices start at 1,
not zero

004

Using other selectors

Now that we’ve worked through a practical example of using selectors to make a page element interactive, let’s run through some of the other ways in which you can use selectors. These examples are all taken from the demo page and refer to the color array we used above. Most of them use the CSS method for demonstration, but you can of course use other jQuery methods on your selected element.

Select all input elements:

$(":input").css("margin", "5px");

Select all button inputs:

$(":button").css("font-weight", "bold");

Select all links to a particular file type, in this case PDFs:

$("[href$='.pdf']").css("color", colors[0]);

Select the first element of a particular type in the document, in this case paragraph:

$("p:first").css("background", colors[2]);

Select the last child of a particular type in its parent element, here a list item:

$("li:last-child").css("border-bottom", "2px "+colors[5]+" solid");

Select every element that matches any of the indicated comma-separated selectors, here a text input or any of the heading elements (h1 to h6):

$(":text, :header").css("background", colors[6]);

Select any element of the type (paragraph) that contains the specified text string:

$("p:contains('intro')").css("color", colors[8]);

Select elements of one type that are siblings of another type (here paragraphs that are siblings of a list):

$("ul ~ p").addClass("note");

Notice that this time we use the addClass method — in most cases this is the preferred option for styling, with the class CSS added to your style code. If you need to carry out more than one line of processing on an element, you do not need to use the selector syntax each time. The more efficient option is to read the selector into a variable:

var last = $("div:last");//last div in doc
last.append("<p class='note'>Hope you enjoyed reading!</p>");
last.css("border", "1px solid "+colors[9]);

Conclusion

It’s easy to remain unaware of features when you’re picking up a new coding resource. Selectors are among the most useful aspects of jQuery, so it’s well worth brushing up on them for any future projects you use the library on.

Sue Smith is a Web/ software developer and technical writer – see BeNormal Development for details. Currently focusing on mobile application development for the Android platform and HTML5, Sue specialises in writing educational material on programming topics for Web publication. Follow Sue on Twitter @BrainDeadAir or email sue@benormal.info. More articles by Susan Smith
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress