santa
santa

Reputation: 12512

Position of TD in TR

I have a look where I style a TD element based on matched content

$(".myTable td:contains('red')").each(function() {
    $(this).addClass('myClass');
            var nth = $(this).index();
});

It works fine. Now I need to style TD in a row below. So I thought I could count the position of this TD and apply to the next TR

$(".myTable td:contains('red')").each(function() {
    $(this).addClass('myClass');

    var tdNth= $(this).index();

    $(this).parent().next('tr').find('td:nth-child(tdNth)).addClass('myClass');
});

However it does not work. What am I missing?

Upvotes: 0

Views: 97

Answers (2)

Anthony
Anthony

Reputation: 37065

If your table rows use th for first column, then the code:

var tdNth= $(this).index();

is going to be the index of the td including that th, so if it's the 3rd column and the 1st column is th, tdNth will be 3 which won't work with:

$(this).parent().next('tr').children('td').eq(tdNth).addClass('myClass');

because eq(tdNth) will select based on index of matching tds, which would be the 2nd in your row above, not 3rd. So instead, use:

var tdNth = $(this).parent().children('td').index($(this));
$(this).parent().next('tr').children('td').eq(tdNth).addClass('myClass');

This will ensure that index for both are based on index of tds and avoids off-by-one issues.

http://jsfiddle.net/55krupq2/3/

Upvotes: 1

Alnitak
Alnitak

Reputation: 339927

You're attempting to "interpolate" a variable into a string constant. That doesn't work.

Whilst you could use string concatenation to build the appropriate :nth-child() pseudo-selector, in my experience doing so is brittle and error prone so I try to avoid doing so wherever possible.

Instead, try:

$(this).parent().next('tr').children().eq(tdNth).addClass('myClass');

The above also avoids the "off-by-one" error your code would have had since .index() returns a zero-based offset but nth-child uses a one-based offset.

Upvotes: 2

Related Questions