jQuery Selectors 2
In this tutorial, we’ll be getting just a little bit more advanced with the selectors.
Children AND highlighting rows
: odd, :first, :last
If we are displaying a large amount of data in a table, we can easily increase the readability by highlighting every other row. Let’s look at this simple table:
<table id="demo" border="1"> <tr> <th>Llanowar Augur</th> <td>Creature - Elf Shaman, Sacrifice Llanowar Augur: Target creature gets +3/+3 and gains trample until end of turn.</td> </tr> <tr> <th>Llanowar Behemoth</th> <td>Creature - Elemental, Tap an untapped creature you control: Llanowar Behemoth gets +1/+1 until end of turn.</td> </tr> ... </table>
We can highlight every other row of this table by adding the following code inside the $(document).ready(function(){…}) area.
$("#demo tr:odd").addClass("highlight");
What does this do? It first finds the id #demo, then it finds all the odd numbered table rows (<tr>). The .addClass(…) method refers to a CSS class highlight. We could easily define this with something like the following between <style> tags:
.highlight { background-color: lightgrey; }
With that same table, we could change our jQuery from $(“#demo tr:odd”) to $(“#demo tr:first”) and similarly with :last to grab the first and the last rows in the table
:first-child, :last-child, (>)
Now, what if we had nested HTML tags and wanted to highlight only certain tags inside the initial tag. Consider the following HTML:
<div id="demo" style="border:1px solid black"> <p> This is inside a <em>p</em> and also a PARENT of the #demo div </p> <p> This is also inside a <em>p</em>, but it's not the first-child! </p> <p> Okay... this is another <em>p</em> inside #demo </p> <p> This is the last child of the #demo div. </p> This is NOT inside it's own <em>p</em>, so it does not count as a child! </div>
Now, if we wanted to highlight the first and last p tags inside the #demo DIV, we execute the following jQuery:
$("#demo p:first-child").addClass("highlight");
$("#demo p:last-child").addClass("highlight");
More interestingly, we can choose to highlight every child with the following code:
$("div#demo > p").addClass("highlight");
Next Time
Lost? Try part 1.
Make use of these selectors in part 3.

February 1st, 2010 at 5:01 AM
[...] jQuery Selectors 2, I talked about how to highlight certain rows in a table. We can build off this to begin a full [...]
July 8th, 2010 at 12:16 PM
[...] Engineer, Researcher. « Inline AJAX Editing jQuery Selectors 2 [...]