Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to select last cell in a column when using rowspan

I have a table like this:

<table>
    <tr><td>Not This</td><td rowspan="3">This</td></tr>
    <tr><td>Not This</td></tr>
    <tr><td>Not This</td></tr>
    <tr><td>Not This</td><td>This</td></tr>
</table>

How can I select just the right-most cells (containing "This") in each row so I can set the border-color?

I tried something like:

table.find('tr > td:last-child').addClass('someclass');

But that selects the last cells on the 2nd and 3rd rows even though they are not the right-most cell.

I am not using border-collapse on my table, and would prefer to avoid it.

like image 860
Code Commander Avatar asked Mar 25 '26 06:03

Code Commander


2 Answers

This one required a bit of trickery:

$(function() {
    $('td:last-child[rowspan]').each(function() {
        $(this).parent().nextAll().slice(0,$(this).attr('rowspan')-1).addClass('skip');
    });
    $('tr:not(.skip) > td:last-child').addClass('someclass');
    $('.skip').removeClass('skip');
});

So, you begin by looking for any td that is a last child and has a rowspan attribute. You iterate over those, counting rows after each one and adding a class to each of those rows to "skip" them. Then you add your class to the last-child cells that aren't in a "skip" row, and finally remove the skip class.

Demo here: http://jsfiddle.net/Ender/rzqEr/

like image 54
Ender Avatar answered Mar 27 '26 20:03

Ender


You should be able to skip the first <td> like so:

$("table tr td:gt(0)").addClass('someclass');
like image 34
cspolton Avatar answered Mar 27 '26 19:03

cspolton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!