SiteCrafting, Inc.
jQuery 1.3 Closest Function
The jQuery function $.closest() is a particularly handy function when doing DOM manipulation. I'll discuss it's power along with an example of it's use.
jQuery has some awesome functions that were added in 1.3, as we have talked about previously. Recently, I've fallen in love with the $.closest() function. $.closest() will traverse up the DOM tree to find the given selector. There are numerous situations where this is useful, so I'll focus on a simple one: adding/removing rows from a table.
Example
Here's a quick overview of what we want to do. First, listen for click events on a button to add or remove a row. We want to use $.live() for this so that our cloned rows will get the events without any extra work. Second, we want to find the parent table row (tr). Then we want to clone the row and insert it afterward. Removing is just the same, only we $.remove() instead of $.clone(), $.insertAfter(). Here's what it would look like.
$('tr .add-table-row').live('click', function() {
var $row = $(this).closest('tr');
$row.clone().insertAfter($row);
});
$('tr .remove-table-row').live('click', function() {
$(this).closest('tr').remove();
});
What's particularly interesting about this code is how stupid simple it is. I say that with affection towards jQuery; it's made the job of browser quirks, complicated algorithms, and DOM manipulation into nothing more then business logic.
Important Notes
Some important things to note about this code. First, the 'tr' in the selector. While this isn't required it does increase the speed of the code, and it guarantees the $.closest() function will work correctly. Second, you may want to give your users a bit of a warning when deleting something important. I suggest putting a confirm dialog of some sort in between your user and the $.remove() function.
by Paul Sayre | 7/23/2009 9:38am | Comments (0)
No comments found.