jQuery Selectors 2

Check out the demo

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">
		<th>Llanowar Augur</th>
		<td>Creature - Elf Shaman, Sacrifice Llanowar Augur: Target creature gets +3/+3 and gains trample until end of turn.</td>
		<th>Llanowar Behemoth</th>
		<td>Creature - Elemental, Tap an untapped creature you control: Llanowar Behemoth gets +1/+1 until end of turn.</td>

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">
		This is inside a <em>p</em> and also a PARENT of the #demo div
		This is also inside a <em>p</em>, but it's not the first-child!
		Okay... this is another <em>p</em> inside #demo
		This is the last child of the #demo div.
	This is NOT inside it's own <em>p</em>, so it does not count as a child!

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 &gt; p").addClass("highlight");

Next Time

Lost? Try part 1.

Make use of these selectors in part 3.

Share this post



2 Responses to “jQuery Selectors 2”

  1. Phillip Napieralski : Clickable Table Rows with jQuery Says:

    […] jQuery Selectors 2, I talked about how to highlight certain rows in a table. We can build off this to begin a full […]

  2. Phillip Napieralski » Blog Archive » jQuery Selectors 1 Says:

    […] Engineer, Researcher. « Inline AJAX Editing jQuery Selectors 2 […]