简体   繁体   中英

How to find adjacent td of a speicifc column of a table

I am trying to control a specific column of a table using jQuery.

I would like to select the next or the previous td contained in the column number 5 starting, for istance, from the second one and change the related text or css properties of the adjecent ones.

$(document).ready(function() {
$('table.pl_res_game tr td:nth-child(5)').eq(0).addClass('change');

The column can contains 3 or more than 100 td. I tried to use the method next() and previous

$('table.pl_res_game tr td:nth-child(5)').eq(0).next();

but I could not select the adjacent ones.

This is the example: FIDDLE

I would like to select all td contained in the column number 5

In this case you just need to remove eq(0) from your current code, as that is restricting the selection to the first td found:

$('table.pl_res_game tr td:nth-child(5)').addClass('change');

Example fiddle


I would like to select the next or the previous td

In this case use prev() and next() to find it:

var $td = $('table.pl_res_game tr td:eq(1)');
$td.next().add($td.prev()).addClass('direct-sibling');

Example fiddle

try modifing the index of the eq() like in the sample below:

$('table.pl_res_game tr td:nth-child(5)').eq(1).css({'background-color':'green','color':'#fff'});
$('table.pl_res_game tr td:nth-child(5)').eq(2).css({'background-color':'green','color':'#fff'});

and so on

You can then use a for loop for the range you want to select:

$(document).ready(function() {
    for (var i=0;i<3;i++){
$('table.pl_res_game tr td:nth-child(5)').eq(i).css({'background-color':'green','color':'#fff'});
}
});  

JSFIDDLE

to select elements form next row
    $('table.pl_res_game tr td:nth-child(5)').eq(0).closest('tr')
                                            .next()
                                            .find('td:nth-child(5)').css({'background-color':'green','color':'#fff'});

FIDDLE

jsut use prev to select previous td of same row
$('table.pl_res_game tr td:nth-child(5)').prev()
                                         .eq(0)
                                         .css({'background-color':'green','color':'#fff'});

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM