Reputation: 42798
How would I use jQuery to find an element (tr
) with the fewest amount of children (td
's) in my table?
Upvotes: 2
Views: 87
Reputation: 21947
$(document).ready(function(){
var tr = $('tr');
tr.sort(function(a, b) {
return $(a).children('td').length - $(b).children('td').length;
});
// $(tr).first() is your TR with fewest TDs
});
Upvotes: 4
Reputation: 14737
I'd probably encapsulate that into a custom jQuery wrapper method.
(function($) {
// blah with function name
$.fn.fewestChildren = function () {
var $this = $(this).filter('tr'),
bookmark = $this.eq(0)
;
$this.not(bookmark).each(function () {
var $t = $(this);
if (bookmark.children('td').length > $t.children('td').length) {
bookmark = $t;
}
});
return bookmark;
};
})(jQuery);
So that I can just use that like:
var foo = $('#mytable tr').fewestChildren();
I'd really love to see a solution without having to make use of a bookmark
variable though.
Upvotes: 1