JavaScript Tutorial Newsletter Do you want to learn how to write code? This is an independent code programming tutorial website. All tutorials are written and distributed for free to whosoever wishes to sign up. There are no ads. Please support us by subscribing to LearnjQuery.org free tutorial updates newsletter.



Join other 5 subscribers

Tutorial 2 - CSS Selectors Walkthrough

 

My name is Greg, as you may already know. I am the author of numerous jQuery tutorials and publications. Your continued readership is much appreciated and keeps me motivated to write more jQuery tutorials.

This newsletter issue is about CSS Selectors, the importance of knowing what DOM is and learning to select elements of all kinds in different ways.

CSS selectors play crucial part in jQuery development. Many people are comfortable with just learning a few, never really reaching the potential of using them in combinations with jQuery functions that further enable us to make complex selections.

You want to learn as many selectors as possible if you want to increase your productivity. But don't learn them all at once. Experiment with one selector at a time, and build your knowledge on your past experience.

Let's consider some of the very basic jQuery selectors:

The first two examples are pretty straightforward. You may have already experimented with these methods.

The third examples shows how we can select BODY by referring to it as parent of DIV it contains. The DIV, in this instance is referred to as a child of BODY.

The function parent() is part of a set of functions for traversing your Document Object Model created by nesting HTML tags within one another.

Other element traversing functions exist, such as next() and previous(). I talk more about them below, but first we need to understand how elements are selected. CSS Selectors operate exclusively on the DOM structure.

What kind of elements can you select?

jQuery selectors can select pretty much any HTML element. And if you understand the basics of DOM (Document Object Model), you are at a great advantage. Using your knowledge of DOM and jQuery selectors together can significantly reduce the time you spend developing dynamic Javascript code.

Here is the basic idea of what DOM looks like. The HTML equivalent of this DOM structure is displayed in the upper left corner.

The DOM is pretty easy to understand. It is very useful for thinking about your jQuery selectors. But it's surprising how many people ignore it. Respect the DOM. Don't ignore it.

CSS Selector code is the first parameter of the main jQuery object. Let's quickly take a look at the definition again:

	
jQuery = function(selector, context) { /* Library code */ }

The selector argument is one of the most frequently used parameters of jQuery. Many people don't even realize that there is a second argument that they can pass, called context. I'll get back to that later in this tutorial.

The selector parameter specifies the CSS selector code. Once the element in question is selected, we can run a function on it.

	
    jQuery('div').hide();

This will select all DIV elements within the BODY branch of the DOM.

If multiple elements have been selected, this function will run on all selected elements. This means, it will hide all DIV elements in BODY, even though BODY is not even a part of the definition. It is assumed that the first selector refers to the BODY branch in DOM. We can explicitly specify BODY in our selector, as you will see in the examples below for the sake of being complete. But it is not always necessary.

Common CSS Selector Examples

Let's take a look at some of the most common jQuery selectors that you are probably going to be using all the time.

Probably one of the most common selectors is the # symbol. It stands for selecting a DIV with an ID specified immediately after the # symbol.

	
    // Select an element that has ID of "dog", and hide it
    jQuery('#dog').hide();

    // Select DIV element that has ID of dog, and hide it
    jQuery('div#dog').hide();

We can always refer to an element with an ID of "dog" as #dog in our jQuery selector. If we want to be specific and select a DIV with an ID of "dog", we can use "div#dog". Of course, this is a matter of semantics. Following the rule that there could (or should) be only one element with a unique ID per webpage, it probably makes no sense prefixing the selectors that start with # with the name of an element.

To traverse the DOM and make sure that we are selecting the right thing, we can use the SPACE ( ) operator. The space operator lets DOM know exactly which branch we want to traverse:

	
    // Hide all DIVs inside BODY, but not BODY itself
    jQuery('body div').hide();
    
    // Hide all DIVs inside first DIV child of BODY, but not DIV child itself
    jQuery('body div div').hide();

    // Hide all DIVs inside first DIV child of BODY whose id is #secret
    jQuery('body div#secret div').hide();

Note that none of the elements before the last space are actually selected. Only the last one is. The values before the last space simply indicate the DOM path to traverse, but the path itself is not selected, only the last element in the path.

CSS Selector Reference

The following diagrams visually explain how many jQuery CSS selectors work. Print it out, you may find it as a useful reference to keep on your desk.

For simplicity's sake, I used only DIV elements to test the functionality of the selectors shown above.

There are a few more selectors I left out from that table. Notice that this table uses spaces and colons. In some cases, there is a space before a colon, in other cases there isn't.

The power of the colon

In this section I want to explore the colon (:) in jQuery selectors. The colon is like a mini helper tool that lets us converge to the element we are searching for with greater precision.

Below I list most of the cases in general when the colon is used:

Selector Real-world Situation Description
:first $("p:first") The first p element
:last $("p:last") The last p element
:even $("tr:even") All even tr elements
:odd $("tr:odd") All odd tr elements
:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)
:gt(N) $("ul li:gt(3)") List elements with an index greater than 3
:lt(N) $("ul li:lt(3)") List elements with an index less than 3
:not(selector) $("input:not(:empty)") All input elements that are not empty
:header $(":header") All header elements h1, h2 ...
:animated $(":animated") All animated elements
:contains(text)    $(":contains('clockwork orange')") All elements containing text 'clockwork orange'
:empty $(":empty") All elements with no child (elements) nodes
:hidden $("p:hidden") All hidden p elements
:visible $("table:visible") All visible tables

For the full list, visit the official jQuery documentation: here

But colon is also widely used with INPUT elements. In many cases, for example, when dealing with radio buttons, check boxes or textareas, some of the rules that apply to blocking elements (such as DIV) do not apply. The number of the colon-based selectors can overwhelm someone who is just starting to learn jQuery. I wouldn't want that to happen to my readers. But I'll get to the other ones as well, as we move forward.

In fact, I created a completely separate newsletter episode to address the issue of colon selectors for input elements. Using the colon to work with input elements will be discussed in an upcoming newsletter episode called Dealing With Input Elements. The content will include type = "text" input boxes, textareas, checkboxes, radio buttons and others. For now, let's see what we can do with elements after we have selected them.

I selected an element, what's next?

Sometimes we want to work with the this object which refers to the object that your Javascript application currently has focus on, during the execution flow of your script. Here is a basic inline CSS example of the this keyword in action:

	
<div id = "iris" onclick = "this.style.background = 'gold'">Iris</div>

Clicking on this DIV will turn its background to gold color.

We can achieve the same exact effect by rewriting it for jQuery use, like this:

	
<div id = "iris" onclick = "$(this).css('background', 'gold');">Iris</div>

When referring to itself, we do not use quotes around the selector. Simply use this as the selector, without quotes.

Because the DIV element has ID of "iris", the same exact effect could be achieved by doing something like:


$("#iris").css('background', 'gold');

In this case, css is the function we want to apply to selected elements. Whatever was selected, will now be liable for receiving the effect caused by the function applied to the selection. Because in this instance we use the css function, which is part of the standard jQuery library, the DIV element's background color will turn to gold.

jQuery offers a large number of functions that can be applied to the elements you have selected. You can hide elements, change their CSS properties; as in the example above, and you can attach events to elements such as onclick or onmouseover.

Let's take a look at some of these functions now.

Function Usage Example Description
css(style, value) css('background', '#ff0000'); Apply a CSS style to an element
hide() $('div').hide(); Hide all DIV elements on the page (display:none)
show() $('div').show(); Show all DIV elements on the page (display:block)
prev() $('div').prev(); Go to previous child, placed side by side in current parent
next() $('div').next(); Go to next child within the current parent
parent() $('div').parent(); Go to the parent of the currently selected element
html() $('div').html('<p>new</p>'); Replace the actual HTML content of an element
text() $('div').text('new text'); Replace the text within an element
animate() $('div').animate({backgroundColor: "#ff0000"}, 1000); Animate background color to red in 1 second

This table lists only some of the functions. I tried to choose some of the more important ones that I use often. There are many more functions related to each specific group of tasks: events, CSS, visual effects, animation, ajax and utilities. Dumping tables with large amounts of functions is not my style of writing a helpful tutorial.

I usually like to explain functions in detail in the context of my tutorials as we move along from one subject to another. This way I have a chance of showing examples of practical uses of these functions. For now try to experiment with the functions from the table above in your own projects.

As you follow my future newsletter episodes, you will gain a deeper understanding of using CSS Selectors. I use practical examples all the time.

Making complex selections elegant

I want to conclude this episode by showing you an example of a complex CSS selection.

The idea came from a real project I am working on where I wanted to update a table cell, based on whether any text located in an input field in an adjacent table cell has just been changed. I wanted to trigger this when the input field in question lost focus.

This would then change the text in an adjacent table cell from ok to ch, an indicator that "the value has been changed for this element". This way later I could simply grab (again, using jQuery) only input fields that have been changed to new values and send it to the script to update them, while ignoring values that were unchanged.

This example will also show you how to attach an event to a text input box, instead of adding onblur directly into the input field by writing HTML code. Those attribute based HTML events such as onmouseover or onmouseout only clutter the HTML code.


<head>
<script type="text/javascript">
  $(document).ready(function()
  {
     $('table td:nth-child(3) input').change(function()
     {
         $(this).parent().prev().html('ch');
     });
  });
</script>
</head>
<table>
    <tr><td>Item</td>       <td>Status</td> <td>Input</td></tr>
    <tr><td>First Name</td> <td>ok</td>     <td><input type = "text"/></td></tr>
    <tr><td>Last Name</td>  <td>ok</td>     <td><input type = "text"/></td></tr>
    <tr><td>Birthday</td>   <td>ok</td>     <td><input type = "text"/></td></tr>
    <tr><td>Location</td>   <td>ok</td>     <td><input type = "text"/></td></tr>
    <tr><td>Occupation</td> <td>ok</td>     <td><input type = "text"/></td></tr>
</table>

As much as the code above will speaks for itself, I want to give you a brief idea of what is going on. First we attach a jQuery event to all input boxes that are located in 3rd column of the table. All of this is possible to do with the jQuery selector 'table td:nth-child(3) input'. This selector alone has just saved us from retyping these events into individual input boxes within the table, which would be a major pain.

After selecting all of these input boxes, we attach the change event to it, and assign it a function. Whatever goes inside the { ... } brackets of that function will execute every time the input field loses focus (when you click out of it, in other words onblur).

Note that the nameless function closure inside the change(...) event will actually be assigned to each individual cell in the third column of this table, one by one (the function is assigned for each table cell in the 3rd column). This is what the table td:nth-child(3) input selector does. It goes into each cell of the third column one by one, using each cell as the starting point.

Let's see what else actually happens here:

We use the jQuery's parent() function. The parent of the selected input box is the TD cell in which it is located.

We now use the prev() function on parent, to go back one TD cell. This is because the previous child of the TD in which the input box is in, is the "status" TD. That's the one we need to update. This means we are now in the "status" TD cell.

Let's modify the status TD cell with a new message, because the input has been modified for that row's input box. We use html('ch') function. The default HTML in the status cell is "ok", and now we change it to "ch" (for: it has been changed!), or also known as "dirty" in the software developer circles.

Of course you can get creative and do whatever you want, change the cell's background color by using css('background','red'), or even insert a custom image icon indicating a "changed" state. The point is that by using DOM's element associations, we were able to traverse the DOM tree backwards and into the element we needed to update. And all without using spiderweb code.

I believe that this example illustrated how much more simple your Javascript development can be using jQuery. Try to stick to similar ideas presented here. Traverse fields using their children and parents, instead of directly accessing them by ID. This can be extremely powerful technique and keeps your code clean and easy to edit.

You have reached the end of this tutorial; I hope you enjoyed reading it as much as I enjoyed writing it. Ha-ha, actually, writing these newsletters is not easy, I spend over 9 hours on each. But I truly do hope it helps someone out there.

The purpose of this newsletter episode is to show you how to effectively use some CSS selectors to make basic, as well as complex selections. If by the end of reading this article you have become a faster jQuery programmer, or learned something new, I have succeeded.

This concludes our discussion of CSS selectors.

© 2014 Copyright LearnjQuery.org.