Search code examples
javascriptjquerynodessiblings

Javascript/Jquery: Cannot target Sibling Node in Table


I have a function that hides/shows a table by clicking on it's header which is contained in a <thead> tag. When clicked the table hides and all that is left is the header, which, by clicking again, can un-hide the table.

I have multiple tables and would like to only have to use on function, instead of writing one for each table. To do this I am trying to pass the arguments (this,this.lastSibling). For some reason this.lastSibling is not targeting any object. I've tried every way of navigating the node tree I can think of, but I cannot target the tbody.

My Javascript/Jquery

function ToggleTable(trigger,target){
    $(trigger).click(function(){
      $(target).toggle();
      ToggleTable(trigger,target)
    });
}

My HTML

<table class="format2" >
    <thead onmouseover="ToggleTable(this,this.lastSibling)">
        <!--Title-->
    </thead>
    <tbody>
        <!--Cells with information in here-->
    </tbody>
    <!--Note No TFooter Tag-->
</table>

<--Other tables similar to the one above-->

Thanks in advance!


Solution

  • I have a function that hides/shows a table by clicking on it's header which is contained in a <thead> tag. When clicked the table hides and all that is left is the header, which, by clicking again, can un-hide the table.

    I'm lost in your current code. But If you want to toggle the visibility of the tbody (or the last child element in your <table> tag you could try this.

    function ready() {
    
      $('table > thead')
        .each(function(e){
          $(this).siblings(':last').hide();
        })
        .click(function(e) {
          $(this).siblings(':last').toggle();
        });
    
    }
    
    $(ready);
    

    Live sample: http://bl.ocks.org/3078240