views:

33

answers:

2

Hi all,

I'm currently working on something like a tree, and I want to be able to fold/unfold children. I guess the most easy way to get this is by using nested lists, but I can't use them because I don't have access to the HTML code. This is the relevant simplified HTML code:

<table>
    <tbody>
        <tr rel="1"><td><a href="#" id="fold">fold</a> item 1</td></tr>
        <tr rel="2"><td><a href="#" id="fold">fold</a> item 1.1</td></tr>
        <tr rel="2"><td><a href="#" id="fold">fold</a> item 1.2</td></tr>
        <tr rel="1"><td>item 2</td></tr>
        <tr rel="1"><td><a href="#" id="fold">fold</a> item 3</td></tr>
        <tr rel="2"><td><a href="#" id="fold">fold</a> item 3.1</td></tr>
        <tr rel="3"><td>item 3.1.1</td></tr>
        <tr rel="3"><td>item 3.1.2</td></tr>
</tbody>
</table>

As you can see, no nested items, but there are 'levels' available, so I guess it should be possible to do what I have in mind. The fold/unfold part is working, f.e. when I click fold on item 1, items with rel >= 2 are hidden. But that's not what I want; I only want to fold the items which rel is higher than the one where I clicked fold, and want to hide all of them until I reach an element which rel is lower or equal to the current rel.

For example, when I click fold in item 1, item 1.1 and 1.2 should be hidden, but item 3.1 should stay visible.

Is there anyone that can help me getting started? Thanks.

Bjorn

A: 

I do not think that you can achieve this with a single selector. This is my approach: http://jsfiddle.net/RrnDG/1/ Note that i changed your id="fold" to class="fold", since having multiple IDs with the same value is invalid. An ID is meant to be unique.

What i am doing here is (basically):

  • get level of the clicked row
  • traverse all following rows. for each do:
    • check if level is higher (e.g. deeper nested); if true, toggle visibility, otherwise abort traversing
elusive
Thanks, this is working, I was trying to solve things way to difficult! :)
Bjorn
Small note: I changed your `fold`-ID to a class, since an ID has to be unique and cannot be used multiple times. I edited my post accordingly.
elusive
I already saw it in the code, fixed it already (but not on SO), thanks for pointing that out.
Bjorn
A: 

something like this should work

$("#fold").click(function()
{
    var _current = $(this).parent().parent();
    var _level = _current.attr('rel');

    _current.nextAll().each(function()
    {
        if($(this).attr('rel') > _level){
            $(this).hide();
        }else{
            // Nested children stopped here, we don't continue
            return false;
        }
    });        
});
Nico