Put generated items into lists

I am still fairly new to Stackoverflow, so forgive me if I am doing this wrong. This question pertains to another question I asked a couple of weeks ago, which was solved at jQuery toggle() with dynamic div ID’s

I recommend you check the link I posted, so you can know what I am talking about.

Read More

So I now have my list of items being generated, I have switched out the “button” code and replaced it so each generated item is a “li” – however, I now have a list of items in my menu that have no order to them. I need to designate some items as top level items, and have other items as sub-items on a drop down menu.

I was thinking that I could perhaps tweak my classes so that when the buttons are generated, top level items have a class and sub-level items have a class, something along the lines of:

<div class="category-1-top-level-item">Main Item</div>
<div class="category-1-sub-item">Sub Item</div>
<div class="category-1-sub-item">Sub Item</div>

<div class="category-2-top-level-item">Main Item</div>
<div class="category-2-sub-item">Sub Item</div>
<div class="category-2-sub-item">Sub Item</div>

Then, perhaps, jQuery could be used to detect the top level item “category-1” and any sub items marked “category-1-sub-item” and then output a properly formatted list:

<ul>
    <li>Top Level Item
        <ul>
            <li>Sub Item</li>
            <li>Sub Item</li>
        <ul>
    </li>
</ul>

Then, of course, that list could be styled with CSS to make a nice drop down menu for sub-items and such.

I don’t know if this would work as a solution or not (if it does then great), but I have been struggling with the code needed to get this working properly.

If someone could help, it would be appreciated so much!

Related posts

Leave a Reply

1 comment

  1. Though verbose, this seems to do what you’re after:

    var topLevel = $('<ul />');
    var subMenus = {};
    
    function getId(el){
        return el.attr('class').split('-')[1];
    }
    
    $('div[class^="category-"][class$="-top-level-item"]').each(function(){
        var topLevelDiv = $(this);
        var id = getId(topLevelDiv);
        var subItems = $('<ul />');
        var li = $('<li />').text(topLevelDiv.text())
            .append(subItems).appendTo(topLevel);
        subMenus[id] = subItems;
    });
    
    $('div[class^="category-"][class$="-sub-item"]').each(function(){
        var subLevelDiv = $(this);
        var id = getId(subLevelDiv);
        var li = $('<li />').text(subLevelDiv.text())
            .appendTo(subMenus[id]);
    });
    
    
    topLevel.appendTo('body');
    

    Working example: http://jsfiddle.net/kobi/UuaSA/