0

I get stuck when trying to implement recursive logic in jQuery--I don't have much practice with it. I have a simple need, which is to nest unsorted lists by class. What I have is two dynamic lists on a page (they're generated by two CAML queries). The first list will be the top level <li> and the second list will be nested. The first list has <li>s with numeric id's and the second list has <li>s with numeric classes that match the id's that they have to be nested under. i.e.:

<ul>
    <li id="10">Parent Item 1</li>
    <li id="14">Parent Item 2</li>
</ul>
<ul>
    <li class="10">Child 1</li>
    <li class="10">Child 2</li>
    <li class="14">Child X</li>
</ul>

There will be an undetermined number of parents and child <li>s over time. Also, if it's better to use a different attr than class for the children that's fine. Ultimately I'll want to add more classes for CSS. Any help would be greatly appreciated.

0

1 Answer 1

1

Working example here: http://jsfiddle.net/rkCKT/

Assuming this markup:

<ul class="parents">
    <li id="10">Parent Item 1</li>
    <li id="14">Parent Item 2</li>
</ul>
<ul class="children">
    <li class="10">Child 1</li>
    <li class="10">Child 2</li>
    <li class="14">Child X</li>
</ul>

this would work:

$(document).ready(function(){
    $('ul.children li').each(function(){
        probable_parent = $('ul.parents li#' + $(this).attr('class'));
        if (probable_parent.length)
        {
            if (!probable_parent.find('ul').length) probable_parent.append('<ul/>');
            $(this).detach().appendTo(probable_parent.find('ul'));
        }
    });
});

Edit:

As soon as you add any classes to the .children lis for presentational reasons, everything will be broken.

For this and half a million other reasons, if your document is HTML5, I strongly suggest using proper attributes for the parent-child relationship. Ideally, the markup would look something like this:

<ul class="parents">
    <li data-itemid="10">Parent Item 1</li>
    <li data-itemid="14">Parent Item 2</li>
</ul>
<ul class="children">
    <li data-itemid="10">Child 1</li>
    <li data-itemid="10">Child 2</li>
    <li data-itemid="14">Child X</li>
</ul>
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for jsfiddle. And good idea adding classes to the ul's, I didn't think of that.
Your code works great! Question for future reference: if I wanted to do this with a table instead of a UL, would it suffice just to replace UL with table and LI with tr?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.