Select any column using jQuery

Is it possible that the user could select any column of the table and that I could do it using jQuery?

I have an example for the game: http://jsbin.com/oluyex/1/edit

Jquery I do not know how to choose the children of each of them:

$(function(){ $("th").click(function(){ $(this).("children").css("background-color","red"); }); }) 

HTML:

 <table id="taula" border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> 
+4
source share
3 answers

To do this, you just need to get the index of the table header, and then use this index to apply the class to each table cell in the column. You will need to go through each row to find the corresponding table cell. - http://jsfiddle.net/BMGKv/

 $('th').click(function() { var th_index = $(this).index(); $('tr').each(function() { $(this).find('td').eq(th_index).toggleClass('highlight'); }); }); 
+3
source

Try the following:

 $(function(){ $("th").click(function(){ var idx = $(this).index()+1; $(this).parent().siblings().find("td").css("background-color","white"); $(this).parent().siblings().find("td:nth-child("+idx+")").css("background-color","red"); }); }) 

Test here

+2
source

The other th are not children of the DOM, although they are visually under the heading. You need to improve your understanding of the data structure of the tree.

In any case, the HTML tables are row oriented, so you need to select each cell of the table in the corresponding column more or less manually:

 $("th").on('click', function () { $(this).closest('table').find('tr').find('td:eq(' + $(this).index() + ')') .css('background-color', 'red'); });โ€‹ 

http://jsfiddle.net/VFWBN/

EDIT: with nth-child you can skip .find('tr') : http://jsfiddle.net/VFWBN/1/

+1
source

All Articles