jsTree Creation With HTML Data

Posted By : Sagar Watts | 18-Sep-2017

We can make use of HTML and Ajax data to create a  tree. We will discuss tree creation using both of the ways mentioned. We can create a simple tree and tree with childs. Also we can  make the tree configuration in HTML itself . Let’s start with simple basic tree creation , then we move on to the tree with childs.


Basic Tree: -  we can make use of unordered list to represent it as a tree structure. To achieve our goal all we need is a <ul> and <li> markup wrapped in a container. All the text written inside the <li> will be converted into the tree nodes.  You can follow the below example to create your own tree:

Once we have a HTML, we can create a tree instance using the method:

                $('#container’).jstree();
        

Node 1 and  Node 2 will be the tree nodes without any childs.


 

Tree with Childs:- To create a tree having nodes with child we need to make a small change in the above shown HTML, we need a <ul> and <li> markup nested in each <li> markup. The nested <li> text will be shown as childs of the parent <li>. The modified HTML will look like:

 

The child 1 and child 2 will appear as the childs of the Node 1. Tree instance can be created in the same way as we created above.

 

Creating tree with AJAX : Apart from the HTML, we can also make use of AJAX to get the HTML content and render a tree structure. The format will be same as of the above example, however the only difference will be that the HTML will be returned from the server. For that we need to use core.data configuration. The configuration for the AJAX will be as :

              
	$('#treeId').jstree({
		  'core' : {
		    'data' : {
		      'url' : 'HTML_URL.html',
		      'data' : function (node) {
		        return { 'id' : node.id };
			      }
			    }
			  }
			});

        
Now that we have created a tree with and without child, we can set the initial state with classes and data attribute. We can use the jstree-clicked class to make the node initially selected. Please note that the class should be used inside <a> tag. In the same way we can make use of  jstree-open class to make any <li> extended initially.
 
Thanks.

About Author

Author Image
Sagar Watts

Sagar is a bright Web App Lead Developer , he has great knowledge of core Java and advance Java. His hobbies are Net Surfing, Listen Music and Reading Books.

Request for Proposal

Name is required

Comment is required

Sending message..