1
votes

I am pretty new to jQuery and CSS and hope someone can help me with the following:

I have a standard HTML table with a colgroup, thead, tbody and several tr's and td's in the body and would like to use a CSS class to hide certain columns.

My CSS class looks like this:

.hideAll
{
    display:none;
}

What is the best / correct way to apply this class ? To the col's in the colgroup, to the th's in the thead, to the tr's or td's in the tbody or to several of them at the same time ?

My table looks something like this:

<table>
    <colgroup>
       <col />
       <col />
       <col />
    </colgroup>
    <thead>
        <tr><th></th><th></th><th></th></tr>
    </thead>
    <tbody>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
    </tbody>
</table>

Many thanks for any help with this, Tim.

4

4 Answers

3
votes

if you know which exactly column you want to hide. Give it a class name.

<table>
<colgroup>
   <col />
   <col />
   <col />
</colgroup>
<thead>
    <tr><th class="target">AAA</th><th>BBB</th><th>CCC</th></tr>
</thead>
<tbody>
    <tr><td class="target">111</td><td>111</td><td>111</td></tr>
    <tr><td class="target">222</td><td>222</td><td>222</td></tr>
    <tr><td class="target">333</td><td>333</td><td>333</td></tr>
</tbody>

Then you can use jquery addClass() method to add your hideAll class to them.

$('.target').addClass('hideAll');

Demo

3
votes

Like @drip already told you, it would be usefull adding some class name to your table's children.

Anyway you can set the given class to your elements like this:

$('myElementSelector').addClass('hideAll');

and then if you want to remove the class, the code will be:

$('myElementSelector').removeClass('hideAll');

For jQuery selector, I suggest you to read jQuery selectors' documentation.

But if you are new to jQuery world and in the future you won't need it so much, you can consider learning KnockoutJS, which elevates you from pure dom management.

Hope it helps :)

0
votes

Pretty much you can just stack them and add the class.

$('col,tr,th,td').addClass('hideAll')

But it really depends which one exactly you want to hide.

If this is just for "try" than this is good. But if have a large project you might consider adding some kind of class to the table and targeting it instead all of the elements trough out the page.

0
votes

http://jsfiddle.net/L4TEq/

I made a simple script which allows you to hide an entire column just giving to a column class="hidden".

This might help and semplify your work.

It's based on elements index. In this way, you can hide all corresponding ths and tds with the same index of the column.