user3145348
user3145348

Reputation: 103

How to get tree structure in jQuery for Parent Child relation in ul list?

Before

<ul>
<li parent-id="0" li-id="16">Anthropology Department</li>
<li parent-id="16" li-id="18">Anthropology Faculty Collections</li>
<li parent-id="16" li-id="23">Shared Collections</li>
<li parent-id="0" li-id="19">Center for Research on Vermont</li>
<li parent-id="19" li-id="24">Collections for Testing</li>
<li parent-id="24" li-id="25">Geology Department</li>

//after i want like this

<ul>
<li parent-id="0" li-id="16">Anthropology Department
    <ul>
        <li parent-id="16" li-id="18">Anthropology Faculty Collections</li>
        <li parent-id="16" li-id="23">Shared Collections</li>
    </ul>
</li>
<li parent-id="0" li-id="19">Center for Research on Vermont
    <ul>
        <li parent-id="19" li-id="24">Collections for Testing
            <ul>
               <li parent-id="24" li-id="25">Geology Department
                </li> 
            </ul>
        </li>
    </ul>
</li>

I would like to match the li-id with parent-id and then if matched parent-id list should be appended to li-id list.

I've tried this so far:

var liid = $('li').attr('li-id');
var parid = $('li').attr('parent-id');
if(liid==parid){
parid.appendTo(liid)
}

Upvotes: 1

Views: 1489

Answers (3)

Mukul Jayaprakash
Mukul Jayaprakash

Reputation: 341

    $("li").each(function () {
    var lid = $(this).attr("li-id");
    var pid = $(this).attr("parent-id");
    var li = $(this);
    if (pid != 0) {
       // alert(pid);
        var theli = $("li").filter("[li-id='" + pid + "']");
        if (theli.find("ul").length > 0) {
            theli.find("ul").append("<li parent-id='" + pid + "' li-id='" + lid + "'>" + li.html() + "</li>");
        } else {
            theli.html("<ul></ul>");
            theli.find("ul").append("<li parent-id='" + pid + "' li-id='" + lid + "'>" + li.html() + "</li>");

        }
        li.remove();
    }
});

Try this code , jsfiddle url : http://jsfiddle.net/mukuljp/Nvguw/

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Try

$("li").each(function(){
 var ul=$("<ul/>");
 ul.append($("[parent-id="+$(this).attr("li-id")+"]"));
 $(this).append(ul);

});

Demo

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388326

Try

jQuery(function($){
    var $ul = $('ul');
    $ul.find('li[parent-id]').each(function () {
        $ul.find('li[parent-id=' + $(this).attr('li-id') + ']').wrapAll('<ul />').parent().appendTo(this)
    });
})

Demo: Fiddle

Upvotes: 2

Related Questions