Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide table column, which applied colspan...?

I read lots question but no match for my situation. Here is my table structure

enter image description here

If I want to hide column A or B below code work for me.

$('table td:nth-child(1),table th:nth-child(1)').hide();
$('table td:nth-child(2),table th:nth-child(2)').hide();

But if I want to remove C or later column it create problem for me. like below code gave me non-relavent output.

$('table td:nth-child(3),table th:nth-child(3)').hide();

enter image description here

Please find fiddle for this Link

like image 718
Manish Jain Avatar asked Apr 11 '26 07:04

Manish Jain


1 Answers

Pure CSS

This can be done with CSS using the :not() and + selectors:

tr :nth-child(3),
tr :nth-child(3):not([colspan]) + :nth-child(4) {
    display: none;
}

JSFiddle demo.

What this does is hide the 3rd child, then hide the element preceding the 3rd child which has no colspan property.

In your table, this will hide cells with content C, 3 and 4.

Update

As BoltClock mentioned in comments, the above CSS would target any :nth-child(n) found within the tr. To ensure this only targets td or th elements, we can introduce the child combinator (>):

tr > :nth-child(3),
tr > :nth-child(3):not([colspan]) + :nth-child(4) {
    display: none;
}

You'll want to use this if your td or th elements contain children of their own.

jQuery

With jQuery you can loop through each tr element, determining whether the first row's matching th element has a colspan property, then processing accordingly. Here I've wrapped this in a function called hideColumn() which accepts an n argument relating to the column you wish to hide:

$(function() {
    function hideColumn(n) {
        var headerColSpan = 1;

        $('tr').each(function(i) {
            var nth = $(this).children()[n-1],
                colspan = $(nth).attr('colspan');

            // Pull ColSpan from first row th element
            if (i === 0)
                headerColspan = colspan || 1;

            if (colspan === headerColspan)
                $(nth).hide();
            else
                for (i=0; i < headerColspan; i++) {
                    $($(this).children()[n-1+i]).hide();
                }
        });
    }

    hideColumn(3);
});

JSFiddle demo.

like image 181
James Donnelly Avatar answered Apr 13 '26 20:04

James Donnelly



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!