0

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!

  • http://stackoverflow.com/questions/2681581/jquery-how-do-i-check-if-an-element-is-the-last-sibling – zod Jul 09 '12 at 18:59
  • http://stackoverflow.com/questions/2126512/last-sibling-in-jquery – zod Jul 09 '12 at 18:59

3 Answers3

0

Assuming all your tables will have the class format2 . Try this:

$("table.format2 > thead").click(function(){
    $(this).next("tbody").toggle();
});

JSFiddle: http://jsfiddle.net/KcY4X/

Chandu
  • 81,493
  • 19
  • 133
  • 134
0

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

0

If you would like to try a solution that utilizes core JavaScript instead of jQuery shims, this might work for you. It's a function I quickly wrote that returns the last sibling that is an HTML element (e.g. not a text node) although you should be able to easily modify it to accept any node in the DOM:

function getLastSibling(el) {
    var siblings, x, sib;

    siblings = el.parentNode.children;
    x = siblings.length;

    while ((sib = siblings[x - 1]) && x >= 0) {
        console.log(sib);
        console.log(sib.nodeType);
        if (sib.nodeType != 1 || sib.tagName == 'SCRIPT') {
            x--;
        } else {
            return sib;
        }
    }

    return null;
}
natlee75
  • 5,097
  • 3
  • 34
  • 39