how to get the traversing path in tree like structure loading from XML in Javascript

I have a tree structure like below.

enter image description here

when i travese through parent to child i want the full path like : Chemistry->Physical chemistry->Particle theory->Particle theory on clicking the particular node. and when we go back or click the Physical chemistry then path will return like that : Chemistry->Physical chemistry

how can we do that. i am using the following function.

function getParents(id) 
{
  var parents = $("#" + id).parents("ul");
  var selector = "";
  for (var i = parents.length-1; i >= 0; i--) {
    //alert($(parents[i]).find('li').find('span').find('a').html());
    selector += $(parents[i]).find('li').parent().find('span').find('a').html() + " > ";
  }

  //selector += "#" + id;
  $('#breadcrumbs').html(selector);
  //return selector;
}

but it goes to wrong direction.

Answers:

Answer

This is a prime example for a recursive function.

function getBreadcrumbs(a) {
    var path = $(a).text(),
        $parent = $(a).parents("li").eq(1).find("a:first");

    if ($parent.length == 1) {
        path = getBreadcrumbs($parent) + " > " + path;
    }
    return path;
}

$("ul a").click(function () {
    $("#breadcrumbs").text( getBreadcrumbs(this) );
});

See it working over here: http://jsfiddle.net/Tomalak/GFfyg/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.