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?
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)
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
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With