Monday, January 19, 2009

Searching tables with jquery

Suppose you have an html table like the one below (name, favorite color) and you want to grab all the favorite colors.

NameFavorite Color
Joeblue
Sallygreen
Mikeyellow
Ziggyorange

Here are some jquery plugin functions that let you do it:

/** find the index of this node among its siblings **/
jQuery.fn.childn = function() { return 1 + jQuery(this).parent().find("> *").index(this); }

/** given a table row, find the cell value under the supplied heading **/
jQuery.fn.column = function(heading) {
    var idx = jQuery(this).parents("table:first").find("th:contains("+heading+")").childn();
    return jQuery(this).find("> *:nth-child("+idx+")");
}

Example:

$("table tbody tr").column("Favorite Color");

Update: use :eq instead of :nth-child! See my follow-up post for details.

No comments: