Angus
Angus

Reputation: 141

jstree get the level of selected node

How can I get the degree/level of the currently selected node? I.e. the number of parents it has.

I have the section which executes on selection of a node as such:

.bind("select_node.jstree", function (event, data) { 
        var nodeInfo = $("#" + data.rslt.obj.attr("id"));
        console.log(data.rslt.obj.attr("id")); // the id of the node
        console.log(nodeInfo.children("a").text()); // the name of the node
                    // the level of the node???
});

Upvotes: 4

Views: 14142

Answers (3)

zb'
zb'

Reputation: 8059

data.inst.get_path().length

1 is root node;

.bind("select_node.jstree",function(e,data) {
      var inst=data.inst;
      var level=inst.get_path().length;
      var selected=inst.get_selected();
      var id=selected.attr('id');
      var name=selected.prop('tagName');
      console.log(name,id,level);
  });

(better to use inst, instead of searching with dom);

$(function () {
	$("#demo1").jstree({ 
		"plugins" : [ "themes", "html_data", "ui", "cookies" ]
	});
	$("#demo2").jstree({ 
		"plugins" : [ "themes", "html_data", "ui", "cookies" ]
	});
  $('#demo1,#demo2').bind("select_node.jstree",function(e,data) {
      var inst=data.inst;
      var level=inst.get_path().length;
      var selected=inst.get_selected();
      var id=selected.attr('id');
      var name=selected.prop('tagName');
      console.log(name,id,level);
  });
    
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
  With id-s:
<div id="demo1" class="demo">
	<ul>
		<li id="phtml_1">
			<a href="#">Root node 1</a>
			<ul>
				<li id="phtml_2">
					<a href="#">Child node 1</a>

				</li>
				<li id="phtml_3">
					<a href="#">Child node 2</a>
				</li>
			</ul>
		</li>
		<li id="phtml_4">
			<a href="#">Root node 2</a>

		</li>
	</ul>
</div>
  Without id-s:
<div id="demo2" class="demo">
	<ul>
		<li>
			<a href="#">Root node 1</a>
			<ul>
				<li>
					<a href="#">Child node 1</a>                   

				</li>
				<li>
					<a href="#">Child node 2</a>
				</li>
			</ul>
		</li>
		<li>
			<a href="#">Root node 2</a>

		</li>
	</ul>
</div>

Upvotes: 5

Edward Corrigall
Edward Corrigall

Reputation: 472

.bind("select_node.jstree", function(e, data) {
    var level = data.node.parents.length;
    var text  = data.node.text;
    var id    = data.node.id;
    console.log(level,text,id);
})
;

Upvotes: 2

Frog Pr1nce
Frog Pr1nce

Reputation: 728

You could also use (in jstree 3.1.0):

.bind("select_node.jstree",function(e,data) {
      var level=data.node.parents.length;     // 1 = root level, 2 = next level down, etc
  });

Upvotes: 8

Related Questions