JQuery Selectors

JQuery is a powerful scripting language that allows you to match HTML elements pretty simplistically.  For instance, JQuery can perform bulk operations against a range of objects.  JQuery perform statements that match elements in a variety of ways.  For instance, the following statements can match elements as shown below:

$("p") //selects any P html element
$("#pid") //selects an element using the ID of an element
$(".pclass") //selects elements using a specific CSS class

JQuery can use the ">" character to navigate through a hierarchy of elements.  Let's take a look at an example.  Below is a simple table structure.

<table id="tbl">
 <thead>
  <tr>
   <th>Name</th>
   <th>City</th>
   <th>State</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Brian</td>
   <td>Columbus</td>
   <td>OH</td>
  </tr>
  <tr>
   <td colspan="3">
    Some more information
   </td>
  </tr>
  <tr>
   <td>Jason</td>
   <td>Iving</td>
   <td>TX</td>
  </tr>
  <tr>
   <td colspan="3">
    Some more information
   </td>
  </tr>
  <tr>
   <td>Susan</td>
   <td>Redmond</td>
   <td>WA</td>
  </tr>
  <tr>
   <td colspan="3">
    Some more information
   </td>
  </tr>
 </tbody>
</table>

I want to use JQuery to do a few things.  First off, every odd row (with the row span of 3) will be hidden upon load.  When the even rows are clicked, a click event will run and show the odd rows.  This is sort of a toggling effect, though I didn't build in toggling yet.

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
 $(document).ready(function() {
  $("#tbl > tbody > tr:odd").hide();
  $("#tbl > tbody > tr:even").click(function(e) {
   var table = document.getElementById("tbl");
   
   table.rows[this.rowIndex + 1].style.display = "block";
  });
 });
</script>

In the example above, the latest code can be found on code.jquery.com.  JQuery uses the $(document) to hook up to the document, which it defines a ready event.  Ready fires when the document is loaded.  Upon loading, a table with the ID of "tbl" is located.  I want to affect all of the child TR rows, but I want to avoid the THEAD element, which is why I navigate to the TBODY.  The odd rows, using the :odd pseudo statement is used to hide the rows with a rowspan="3".  Even rows tap into a click event, showing the row.

This is one way to use JQuery scripting.

Published Friday, February 20, 2009 4:29 AM by bmains
Filed under: ,

Comments

No Comments