Moving and inserting elements revisited
Over the course of the coming examples, we will build a flexible sorting mechanism that works on each of the columns. To do this, we will use the jQuery DOM manipulation methods to insert some new elements and move other existing elements to new homes. We will start with the most straightforward piece of the puzzle: linking the table headers.
Adding links around existing text
We'd like to turn the table headers into links that sort the data by their respective columns. We can use jQuery's .wrapInner()
method to add them; we recall from Chapter 5, Manipulating the DOM, that .wrapInner()
places a new element (in this case an <a>
element) inside the matched element, but around child elements:
$(document).ready(function() { var $table1 = $('#t-1'); var $headers = $table1.find('thead th').slice(1); $headers .wrapInner('<a href="#"></a>') .addClass('sort'); });
Listing 12.1
We skipped the first <th>
element of each table...