Ronnie Jespersen Ronnie Jespersen - 1 year ago 62
jQuery Question

jquery run through tables and only do something if 2x TDs

I am in a special "problem" here. Ti accommodate a request from a client I need to do the following. Run through all tables on a page. For each table check if it has exactly 2 TD's. If it does then I need to make a "read more" implementation.

I have used this on another page where I know the exact div's I want to collapse and expand.

if ($(this).height() > adjustheight){
id =;
id = id.split("_");
$("#expand"+id[1]).toggle(function() {
id =;
$(".more-block"+id).css('height', 'auto').css('overflow', 'visible');
$('html, body').animate({scrollTop: $(document).height()}, 'slow');
$(".frontpage_box").css('height', '');
}, function() {
id =;
$(".more-block"+id).animate({height: adjustheight}, "slow", function(){
$(".more-block"+id).css('height', adjustheight).css('overflow', 'hidden');

$(".more-block").css('height', adjustheight).css('overflow', 'hidden');

Any ideas?
When I run through the TD's I could just add the classes "more-less" and "more-lessexpand1" (number is increment). Is this possible? I am not sure how to run the tables and only do this if two TD's is found and only do this last bit on the second TD.

Oh and by the way... its important its only the second TD that collapses and expands. The left one is not allowed to. I might be able to solve this last bit if someone could help me find the TD's of interest.

Please help

Answer Source

" I might be able to solve this last bit if someone could help me find the TD's of interest."

Something like this will find the table(s) of interest, assuming you don't have nested tables:

$("table").each(function() {
   var $tds = $(this).find("td");
   if ($tds.length != 2)
   // this is a table with exactly two cells, so do something
   // $tds.eq(0) will reference first td;
   // $tds.eq(1) will reference second td;
   // So to add the classes to the second cell...
   $tds.eq(1).addClass("more-less more-lessexpand1");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download