Search code examples
javascriptjqueryhtml-tableshow-hide

JQuery hide table column


I am trying to hide a specific column of html table after it's contents are loaded. Table html is created dynamically and loaded with JQuery. This part works as expected.

let cur_grid = document.getElementById('grid1')
// table html is created.
let str_tbl_html = '<table id="tbl_grid1"><tbody><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr></tbody></table>'
$.when($(cur_grid).html(str_tbl_html)).done(function() {
  console.log('hide 3rd column')
  $('#tbl_grid1 tr td:nth-child(3)').hide()
  // also tried
  $('#tbl_grid1').find('td:nth-child(3)').hide()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='grid1'></div>

I don't get any errors but 3rd column is not hidden.


Solution

  • Don't trust Deferreds to determine when DOM elements have been drawn to the screen. Since you are using let I assume you can use modern JavaScript like onanimationstart. You can use this with CSS animations to determine when the table has actually been drawn.

    @keyframes any-animation {
      from {opacity: 0.99;}
      to {opacity: 1.0;}
    }
    
    table {
      animation-name: any-animation;
      animation-duration: 0.001s;
    }
    
    
    let cur_grid = document.getElementById('grid1')
    
    // table html is created.
    let str_tbl_html = '<table id="tbl_grid1" onanimationstart="hideThirdColumn()"><tbody><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr></tbody></table>'
    
    function hideThirdColumn() {
      $('#tbl_grid1 tr td:nth-child(3)').hide()
    };
    

    I learned this trick on an old blog post on css-tricks.com (he credits a few other bloggers on that page as well).