HTML and CSS Reference
In-Depth Information
The previous two sections on selection and traversal have shown you how a set of elements
can be selected from the document. This section is going to introduce you to the ways you
can manipulate documents once you have a set of elements to work with.
If you look at the tasks.html document you will see that the second row in the table has a
class called even assigned to it. The basic idea is that every second row in the table will
be given the even class, and this will change the background colour of the row to make the
table easier to read.
As mentioned previously, a real world application would be better off performing this func-
tionality with CSS, but performing this with jQuery provides a nice introduction to DOM
Before beginning this section, remove the even class from the second row in the table . After
this, refresh the tasks.html page in the browser and ensure all the rows have a white back-
In order to manipulate elements we must first select them. The selection criteria should be
fairly standard by now. We first find all the even rows in the body of the table (this ensures
we do not change the background of the header row):
> $('tbody tr:even')
This will actually return two rows, since jQuery is counting from 0 the first row in the table
and the third row in the table are returned. This still suits our needs, since our only real con-
cern is that every second row is shaded.
We can then manipulate these rows as following:
> $('tbody tr:even').addClass('even')
As soon as you execute this code you will see the DOM update, and the relevant rows of the
table will be shaded with a new background color.
In addition to adding classes, we can also remove classes with removeClass and toggle
classes with toggleClass . Toggling is a particularly useful technique since it removes the
class if the element already has it, or adds the class if the element does not already have the
class. This will be used in examples later in this topic.
Another requirement we may wish to implement is to add a red * next to the label for all
mandatory fields. We know how to find all the mandatory fields; they are the ones with a
required attribute (regardless of the value assigned to this attribute):
> $('[required]')
Search WWH ::

Custom Search