CSS Mastery
Harness the power of CSS to achieve this effect by utilizing the :not()
and +
selectors:
tr :nth-child(3),
tr :nth-child(3):not([colspan]) + :nth-child(4) {
display: none;
}
Check out the JSFiddle demo here.
This code snippet hides the 3rd child element, followed by hiding the preceding element only if it does not have a colspan
property.
In your specific table scenario, cells containing content such as C
, 3
, and 4
will be hidden.
Enhancement
A welcomed insight from BoltClock highlighted that the initial CSS would affect any :nth-child(n)
within the tr
. To exclusively target td
or th
elements, we introduce the child combinator (>
):
tr > :nth-child(3),
tr > :nth-child(3):not([colspan]) + :nth-child(4) {
display: none;
}
If your td
or th
elements have their own children, employing this modification is advised.
JQuery Excellence
For those inclined towards JQuery, an alternative approach involves iterating through each tr
element. The script evaluates whether the first row's corresponding th
element possesses a colspan
attribute, making decisions accordingly. Encapsulated in a function named hideColumn()
, you can specify which column to conceal using the n argument:
$(function() {
function hideColumn(n) {
var headerColSpan = 1;
$('tr').each(function(i) {
var nth = $(this).children()[n-1],
colspan = $(nth).attr('colspan');
// Extract ColSpan value 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);
});
Experience the JSFiddle demonstration here.