If your code looks like this and it comes before the relevant elements in either the head
or body
sections, then the issue is that the script runs before the DOM nodes are created.
To fix this, you can either place the code inside $(document).ready()
:
<script>
$(document).ready(function(){
$('.evenTd').hide();
});
</script>
Or you can move the script after the elements in the HTML on which it should act:
<body>
<table>
<tr>
<td>itemOne</td>
<td class="evenTd">itemTwo</td>
</tr>
</table>
<script>
$('.evenTd').hide();
</script>
</body>
Keep in mind that adding or removing individual table cells may cause layout issues, so it's recommended to hide descendant elements of the specific td
instead of the td
itself.
For instance, with the current HTML structure:
<table>
<tr>
<td>itemOne</td>
<td class="evenTd"><div>itemTwo</div></td>
</tr>
</table>
And using the following jQuery:
$(document).ready(function(){
$('.evenTd div').hide();
});
You can see the result here, where only the visible td
takes up the row-space.
Another option is to simply hide the content of the td
without affecting its visibility on the page:
$(document).ready(function(){
$('.evenTd div').css('visibility','hidden');
});
View the result here.
If you plan to restore visibility at some point, consider adding or removing a class on the td
and handling the styles with CSS for each state:
$(document).ready(function(){
$('.evenTd').addClass('hidden');
$('tr').on('click', 'td.evenTd', function(){
$(this).toggleClass('hidden');
});
});
Check out the JS Fiddle demo for more details.