Using CSS Selectors

A great strength of jQuery is the ease in which parts of a HTML document can be selected. Once part of the document is selected, jQuery can manipulate that HTML in various ways.

Selection is done using the $(construct). The parameters passed into the $(construct) is typically a CSS selector. That is it could be a HTML selector, class selector, id selector or compound selector. Ie

$('p') – select all the HTML paragraph elements

$('.highlight') – selects all HTML elements of class ‘highlight’

$('#footer') – selects the HTML element of ID ‘footer’

Like CSS selectors you can be more or less specific in your selection. For example using a HTML selector like $(‘p’) would target every <p> element. Whereas using an ID selector (that should only appear once in the document) will only select the HTML element which has that ID selector.

Adding a New Class Dynamically with addClass()

The addClass method allows jQuery to dynamically add a new class to a matched HTML element.

Syntax
.addClass(className)

Where className is one or more class names to be added to the class attribute of each matched element.

It’s important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

Assuming that a CSS class called ‘highlight’ has been declared ie:

CSS

.highlight{
	color:#FFF;
	background-color:#039;	
}

On document ready, HTML <p> elements are assigned the class ‘highlight’.

Javascript

<script>
     $(document).ready(function(){
       $("p").addClass('highlight');
     });
</script>

JSFIDDLE Demo

Tech Note: As there are many <p> elements in the document you may expect some kind of loop construct to identify them all. Not with jQuery as it uses a technique known as implicit iteration that is designed to work with sets of objects.

Removing a Class Dynamically with removeClass()

The reverse of addClass(). Takes the class to be removed as its parameter.

Syntax
.removeClass(className)

On document ready, <p> elements will have the class ‘highlight’ removed.

Javascript

<script>
     $(document).ready(function(){
       $("p").removeClass('highlight');
     });
</script>

jQuery Custom Selectors – ‘eq’ and ‘nth-child’

As well as CSS selectors jQuery has its own set of custom selectors. These have syntax similar to CSS pseudo-classes. The ‘eq’ selector takes a numeric parameter that represents the occurrence of the match – note these are an array, such that the first match is 0, the second match is 1 etc.

To select the first paragraph and assign it the class ‘highlight’ we would do the following:

jQuery

<script>
     $(document).ready(function(){
       $("p:eq(0)").addClass('highlight');
     });
</script>

Two useful custom selectors are : odd and : even. These are commonly used for creating stripy tables.

Tech Note: The ‘odd’ and ‘even’ selectors used Javascript’s zero based numbering – so the first row is actually ‘’even’ –ie zero, the second row is actually ‘odd’ ie one.

CSS

tr{
	background-color:#CC9;	
}
.alt{
	background-color:#666;	
}

The following inside the $document(‘ready’) would give any table in the document stripes.

jQuery

$("tr:odd").addClass('alt');

As ‘odd’ is zero based it will add the ‘alt’ class to the second row (what it thinks off as row 1).

If you have multiple tables then the tables stripes may look a little strange as they will pick up the striping where it was left off.

An alternative solution is to use the ‘nth-child’ CSS selector. This selects the nth child of its parent. For example with a HTML list as follows:

HTML

    <ul class="myList">
      <li>Apples</li>
      <li>Pears</li>
      <li>Bananas </li>
    </ul>

We could use the selector:

jQuery

$('ul.myList li:nth-child(2)').addClass('highlight');

The above would look for second list item <li> HTML element, in this case ‘Pears’, and add the class ‘highlight’ to it.

The ‘nth-child’ selector takes numbers as its parameters but can also take ‘odd’ or ‘even’. The nth-child selector is one-based as opposed to the array zero based ‘eq’ selector. So the following would add the ‘myClass’ class to the second row.

jQuery

$("tr:nth-child(even)").addClass(myClass);

jQuery Events

Javascript and jQuery are all about adding interaction to HTML documents. We have already seen $(document).ready and this is in effect an event triggered when the HTML document is loaded and ready to be manipulated via the jQuery.

The ‘click’ method requires a handler – that is a function that will response to the event been triggered. This is most frequently done as an inline function ie:

jQuery

$("p").click(function(){
		// do something
});

Note for testing you may want to use the Javascript method alert(). This is used to output values to the alert box and is a cheap and cheerful way of debugging your code. The above example with an alert would look as follows:

jQuery

$("p").click(function(){
		alert('testing event');
});

You may also use console which is a bit subtler.

jQuery

$("p").click(function(){
		console.info('testing event');
});

Click is actually a shorthand version of the on method. The jQuery on method can take two parameters –

Syntax
.on(eventType, functionToCall)

As such the on version of our example would be:

jQuery

$("p").on('click', function(){
		// do something
});

JSFIDDLE Demo

Within jQuery there are shorthand event handlers for all the standard DOM events.

  • blur
  • change
  • click
  • dblclick
  • error
  • focus
  • keydown
  • keypress
  • keyup
  • load
  • mousedown
  • mouseout
  • mouseover
  • mouseup
  • resize
  • scroll
  • select
  • submit
  • unload

We have also already seen the .ready().

The following click event is triggered when any <p> is clicked. All the <p> elements then have the ‘highlight’ class added.

jQuery

<script>
     $(document).ready(function(){
       $("p").click(function(){
		$("p").addClass('highlight');
});
     });
 </script>

This means ‘me’ – the this keyword

A more useful example would make use of this. The ‘this’ keyword refers to the current object – in our example the specific paragraph clicked.

jQuery

<script>
     $(document).ready(function(){
       $("p").click(function(){
		$(this).addClass('highlight');
});
     });
 </script>

Chaining with jQuery

Another fantastic feature of jQuery is ‘chaining’. By ‘chaining’ we are referring to jQuery’s ability to link two or more actions into a single action. For example, the following would select the content of ID ‘infoPanel’ and then run the show method and addClass methods against it.

jQuery

$("#infoPanel").show('fast').addClass('myClass');

The jQuery selector contains the modified results of each action that runs before running the next action. The delay action can be placed in a chain to pause the chain for a given duration in milliseconds.

jQuery

$("#infoPanel").show('fast').delay(5000).hide('slow');

JSFIDDLE Demo

Note that delay will not help you in all instances but you can use the queue() action as follows:

jQuery

$("#msg").addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
    next();
});

JSFIDDLE Demo

We will see the Javascript action setInterval later on which is a more robust option.

Leave a Comment