How to handle parent nodes and child nodes in tree using javascript

by kalai 2008-01-19 18:58:31

Generate a javascript file by querying all the parents with parentid zero and childs of each parent in the table and store it in an array separated by delimiter. After creating javascript file with parents and childs, it will be easy to retrieve hierarchy of child belonging to a particular parent.

Consider a simple example

id name parentid
1 Php 0
2 Perl 0
3 ASP 0
4 Php Script 1
5 Php code 1
6 perl Script 2
7 Asp script 3
8 Asp code 3

Retrieve all the parent name in the above table with the parentid '0' and all the childs belonging to the each parent and store as an array seperated by delimiter in javascript file. This can be automated by writing code to query the database and generate the javascript file with parent and child nodes.

Consider the javascript file generated for above table as tree.js and the content will be as shown below

In tree.js

var child = new Array();
child[0] = "::PHP::1::#::Perl::2::#::ASP::3::";
child[1] = "::PHP Script::4::#::PHP code::4::";
child[2] = "::Perl Script::6::";
child[3] = "::PHP::7::#::Perl::8::";


You can create seperate function for your required task for example, function to retrieve hierarchy of child belonging to particular parent or parent for a particular child and so on.


Below i am going to explain a simple function to retrieve childs for a particular parent by passing parentid.

function getChilds(id){
var childarray = new Array();
if(child[id]){
childarray = child[id].split("#");
}
return childarray;
}

var parentid=1;
var childs = getChilds(parentid);
for(var j=0;j<childs.length;j++)
{
var arr2=(childs[j].split("::"));
var cname = arr2[1];
document.write(cname);

}

Result:
Php Script
Php Code

Tagged in:

6778
like
0
dislike
0
mail
flag

You must LOGIN to add comments