JQuery Treeview example using HTML Ul li elements

jquery-treeview

To display large number of data we prefer to use Treeview. Let’s take an example where we want to show all those countries & their respective states where we have our customers. In the below example I created the same demo. This Treeview is simply created using Jquery. Using this Treeview you can show any level of data hierarchy.

Jquery is an advanced programming language. For a Jquery professional it is very simple to create a Treeview. Look at the example below here I used only 5 to 6 lines of codes to create a Treeview. The logic I implemented here is so straight forward. In HTML I have ul & li elements which represents data for my Treeview. UL elements inside li elements are sub nodes. Using Jquery document.ready method initially I am tracking all the li elements & inside the li elements which ul elements length is greater than zero I am adding a class “node” for them.

Then in the next loop I am detecting the li elements with class “node” and for their anchor tags click event binding toggle class “active”. To show the expand & collapsible feature smooth I used slideToggle with slow.

jquery-treeview.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>A simple JQuery Treeview for your Website</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.treeview li').each(function() {
if($(this).children('ul').length > 0) {
$(this).addClass('node');
}
});

$('.treeview li.node > a').click(function() {
$(this).parent().toggleClass('active');
$(this).parent().children('ul').slideToggle('slow');
});
});
</script>
</head>
<body>
<div class="treeview">
<ul>
<li><a href="#">Pakistan</a>
<ul>
<li><a href="#">Faisalabad</a></li>
<li><a href="#">Karachi</a></li>
<li><a href="#">Gujranwala</a></li>
</ul>
</li>
<li><a href="#">India</a>
<ul>
<li><a href="#">Odisha</a>
<ul>
<li><a href="#">Bhubaneswar</a></li>
<li><a href="#">Cuttuck</a></li>
<li><a href="#">Balasore</a>
<ul>
<li><a href="#">Balasore Golei</a></li>
<li><a href="#">MPC College Road</a></li>
<li><a href="#">FM University Road</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">West Bengal</a></li>
</ul>
</li>
<li><a href="#">Nepal</a>
<ul>
<li><a href="#">Kathmandu</a></li>
<li><a href="#">Bharatpur</a></li>
</ul>
</li>
</ul>
</div>
</body>
</html>