Open one node and all its parents using jstree

I am trying to use jstree and let one node and all its parents be open when the page opens. Here is the html code I used for testing.

    <div id="treeTask">
       <ul>
          <li id="node_37"><a href="#">TEST1</a>
              <ul>
                  <li id="node_38"><a href="#">TEST2</a></li>
                  <li id="node_39"><a href="#">TEST3</a></li>
              </ul>
          </li>
      </ul>

      <ul>
          <li id="node_3"><a href="#">TEST1</a>
              <ul>
                  <li id="node_4"><a href="#">TEST2</a></li>
                  <li id="node_6"><a href="#">TEST3</a></li>
              </ul>
          </li>
      </ul>
   </div>

And here is the jstree initialization call and open node.

 $(function () { 
        $("#treeTask").jstree();

        $("#treeTask").bind("ready.jstree", function (event, data) { 
            $("#treeTask").jstree("open_node", $("#node_4"));

            if((data.inst._get_parent(data.rslt.obj)).length) { 
                data.inst._get_parent(data.rslt.obj).open_node(this, false); 
              }  
        }); 

  });

I manipulated the code for a while, but could not get it to work. I would really appreciate if anyone could help.

Many thanks!

+4
source share
3 answers

You can use the built-in function _open_to:
http://www.jstree.com/api/#/?q=open_to&f=_open_to%28obj%29

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
  data.instance._open_to('node_4');
}); 
+8
source

Based on @maddin's solution, I updated it to support any number of parental levels.

jsFiddle

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
  $("#treeTask").jstree('open_node', 'node_4', function(e,d) {
    for (var i = 0; i < e.parents.length; i++) {
      $("#treeTask").jstree('open_node', e.parents[i]);
    };
  });
}); 

, a node, . :

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
  $("#treeTask").jstree('select_node', 'node_4');
}); 
+3

, :

fiddle

$("#treeTask").jstree().bind('ready.jstree', function (event, data) { 
 $("#treeTask").jstree('open_node', 'node_4', function(e,d) {
     if(e.parents.length){
         $("#treeTask").jstree('open_node', e.parent);
     };
  });
}); 
+2

Source: https://habr.com/ru/post/1569068/


All Articles