Web Development with jQuery®

(Elliott) #1

Filtering a Selection (^) ❘ 53
If a selection results in nothing, jQuery will return an empty array, and you can then check the
length property to see if anything were selected.
if (!yesterday.length)
{
If there were no adjacent preceding element, you need to move to the previous row. To do that, you
start with the representing today, and then you move up the DOM from there to that element’s
parent element using jQuery’s parent() method, which will be a element. When you arrive at
the element, you move backward in the DOM to the preceding element. You then look at
that element’s children elements using jQuery’s children() method, which will, of course, all
be elements. You then limit the selection of elements to the very last one using the eq()
method. Because we’re counting from zero, and there are 7 days in a week, that will make the last


element the sixth in the selection. Like last time, you provide selectors to the parent(), chil-
dren(), and prev() methods just to provide more context and information in your programming.
var lastWeek = today.parent('tr').prev('tr');
if (lastWeek.length)
{
yesterday = lastWeek.children('td').eq(6);
}
}
It is still possible that there is no element representing yesterday because today could be the fi rst
of the month and thus could occur as the fi rst child of the fi rst element. So, another check for
length ensures that a element has been selected to represent yesterday. When it is determined
that a element for yesterday exists, it is assigned the class name calendarYesterday.
if (yesterday.length)
{
yesterday.addClass('calendarYesterday');
}
Now that you have fi gured out which, if any, element will represent yesterday, the next step
is fi guring out which element will represent tomorrow. This time you move forward a
element by using jQuery’s next() method on the selection representing today, and this will reference
the adjacent following element. Any selection is assigned to a variable called tomorrow.
var tomorrow = today.next('td');
As with yesterday, you are not certain that there is a element that is adjacent and following
the element representing today, so again you check the length property to see if a selection
were made.
if (!tomorrow.length)
{
If there is no element, you again move up the DOM to the parent element from the
element representing today, and you proceed to the next element using next(). Then you look
at that element’s children via children() (if there is a next row in the fi rst place), and you limit
[http://www.it-ebooks.info](http://www.it-ebooks.info)
Free download pdf