3

a simple demo

Trying to build a plugin effect that will some what look better than this when its ready.

Note the numbers 0, 1, 2.

They are simple indication of level the element currently is in. 0 denoting the top level and 2 the least. Check the demo here.

Every time I click on a column, it becomes the main columns (thus gaining 0 as its level) and rest of the columns are leveled using the same rule. If you see the snippet I am using to do that, it is very ugly.

$("li").click(function() {
    $(this).html(0);

    //denote the first level
    $(this).next().html(1);
    $(this).prev().html(1);

    //denote the second level
    $(this).next().next().html(2);
    $(this).prev().prev().html(2);    

    //denote the third level
    $(this).next().next().next().html(3);
    $(this).prev().prev().prev().html(3);    

    //denote the fourth level
    $(this).next().next().next().next().html(4);
    $(this).prev().prev().prev().prev().html(4);    
});

I absolute hate it. What if the number of my column grow, I am in trouble then. I need something neat to traverse up the tree structure (i.e like .closest("li")) and below as well. With every column, getting their specific level of markup once the main column changes.

Starx
  • 77,474
  • 47
  • 185
  • 261
  • As Felix is saying, you should change the question title as you are only interested in traversing siblings. Or we don't understand the question. – unludo Feb 09 '12 at 12:43

1 Answers1

3

You can use prevAll [docs] and nextAll [docs]:

$(this).prevAll().each(function(i) {
    $(this).text(i+1);
});

$(this).nextAll().each(function(i) {
    $(this).text(i+1);
});

DEMO

Btw. you are not traversing up or down the tree, you are always staying at the same level.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @Starx: I don't understand what you mean. – Felix Kling Feb 09 '12 at 12:35
  • Isn't .next(), .nextAll() the traversing function of jquery? Anyways, they are working for my case. Thanks. BTW, is there a way to combine .nextAll() & .prevAll()? – Starx Feb 09 '12 at 12:43
  • @Starx: Yes, these are traversing methods, but you are not traversing the tree up or down (don't confuse the HTML representation with the actual DOM representation). All the `li`s are at the same level. Traversing "up" would be to go to their parent. I was thinking about a way to combine these too, but then computing the index would be more difficult. Depending on what you want to do, you might just want to get all siblings with `$(this).siblings()`. – Felix Kling Feb 09 '12 at 12:47