Tutorial :jQuery conditional selector for table rows


I have a table with data in:

<td> item </td><td> order code </td><td> price </td>

I'm processing the table with jQuery which needs to find the order code:

$.each($('.productList tbody tr'), function() {      var orderCode = $(this).find('td:eq(1)').html().trim();      // do stuff  });  

If there are no products, the table shows a message:

<td colspan="3"> There are no products to display </td>

The above row causes the jQuery function to bomb out. What's the most robust way to use a conditional selector to ignore the "no products" row? Is there a selector for colspan="1" or colspan is not set or whatever it would need to be?


Don't refine your selector, it won't scale well because jQuery will have to evaluate every child element. Avoid the error instead...

$('.productList tbody tr').each(function() {      var orderCode = $(this).find('td:eq(1)');       if(orderCode.length > 0) { // Make sure it exists       orderCode = orderCode.html().trim();        // do stuff      }  });   


Like this:

$('.productList tbody tr:has(td:nth-child(2))').each(function() {      ...  });  

This will only select <tr> elements that have a <td> that is the second child of its parent. (the nth-child selector is one-based)


If you can change how you generate the table, using classes is a cleaner solution:

<td class="item-name"> item </td>  <td class="order-code"> order code </td>  <td class="item-price"> price </td>  

Then select only the desired class:

var orderCode = $(this).find('td.order-code').html().trim();  if(orderCode)  {    //do stuff  }  

This will also give you increased flexibility in styling the table with CSS, and your code won't break if you add or reorder columns.


You could test how many tds there are:

$.each($('.productList tbody tr'), function() {      var tds = $(this).find('td');      if(tds.length >= 2) {          var orderCode = tds.eq(1).html().trim();          // do stuff      }  });  


Use the .attr() method. Check out api.jquery.com and that should help you be able to figure out how to get the colspan attribute from your cells.


More filtration to what SLaks has written

$("table tbody tr td:nth-child(2):contains('code')")

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »