Fadi Nouh Fadi Nouh - 1 month ago 6
Ajax Question

Recursive Function - jQuery , get Links

I have a problem in recursive function for listing (folders & links )
every Folder has links , and maybe every folder has subfolders too,

My problem is that i cant display the links inside thier related folders , my code is only listing the folders without the links
https://jsfiddle.net/9vxa6x8u/1/

here is my code :

function buildTree(jsonUrl) {

function tree(treeData) {
var mainUl = $('<ul>');
$.each(treeData, function( index, folder ) {
id = "folder"+ folder.id;
var li =$('<li id="'+id+'" >');
ul = $('<ul>');
ul.append(li.text(folder.name).append(tree(folder.subFolders)));

$.each(folder.links, function( index, link ) {
ul.append($('<li>').text(link.name));
});
mainUl.append(li);
});
return mainUl;
}

$.ajax({
url: jsonUrl,
dataType: "json",
type: "get",
success: function (data) {
$('#links-tree').append(tree(data));
},
error: function (e) {
console.log(e)
},
});
}

Answer Source

Check this, Is this what you want to achive. Please refer this jsfiddle

Just made changes in following

function tree(treeData) {
    if (treeData) {
      var mainUl = $('<ul>');
      $.each(treeData, function(index, folder) {
        id = "folder" + folder.id;
        var li = $('<li id="' + id + '" >');
        ul = $('<ul>');
        li.text(folder.name);
        ul.append(li.text(folder.name).append(tree(folder.subFolders)).append(tree(folder.links)));

        mainUl.append(li);
      });

      return mainUl;
    }
  }