I have a data, that I supply to JStree in <ul>
and <li>
. My Javascript functions are:
function displayData(data){
//your codes to parse and display json data in html table in your page.
if (data !=null || data!=undefined){
var myDiv = document.getElementById("myTree");
myDiv.innerHTML = data;
makeTree();
console.log(data);
}
else{
console.log("No such data!");
}
}
function makeTree(){
$('#treeDiv').removeAttr('hidden');
var tree = $("#myTree");
$("html, body").animate({ scrollTop: 0 }, 500);
tree.bind("loaded.jstree", function (event, data) {
tree.jstree("open_all");
});
$('#myTree').jstree({
"plugins": ["checkbox"]
});
};
When I first call the function display data with the data :
<ul>
<li>NodeB
<ul>
<li>NodeA
<ul>
<li>NodeC</li>
</ul>
<ul>
<li>NodeD</li>
</ul>
</li>
</ul>
</li>
</ul>
I get a JStree like on this picture: . But when I choose another data and call the display data function again, the data is shown as HTML only. How can I hold the JStree plugin enabled? Thank you.
If you remove the older element of jstree from dom, and create it again it works.
function displayData(data) {
//your codes to parse and display json data in html table in your page.
if (data != null || data != undefined) {
var myDiv = document.getElementById("myTree");
var newDiv;
var parentNode = myDiv.parentNode;
if (parentNode) {
parentNode.removeChild(myDiv);
newDiv = document.createElement('div');
newDiv.setAttribute('id', 'myTree');
parentNode.appendChild(newDiv);
} else {
newDiv = myDiv;
}
newDiv.innerHTML = data;
makeTree();
console.log(data);
} else {
console.log("No such data!");
}
}
function makeTree() {
var tree = $("#myTree");
$("html, body").animate({ scrollTop: 0 }, 500);
tree.bind("loaded.jstree", function(event, data) {
tree.jstree("open_all");
});
$('#myTree').jstree({
"plugins": ["checkbox"]
});
};
var test1 = '<ul> <li>NodeB <ul> <li>NodeA <ul> <li>NodeC</li> </ul> <ul> <li>NodeD</li> </ul> </li> </ul> </li> </ul>';
var test2 = '<ul> <li>NodeB-1 <ul> <li>NodeA-2 <ul> <li>NodeC-3</li> </ul> <ul> <li>NodeD-4</li> </ul> </li> </ul> </li> </ul>';
displayData(test2);
setTimeout(function() { displayData(test1); }, 4000);
I have created a fiddle also : https://fiddle.jshell.net/brb44wkh/1/
I will check if we have better way of doing it. Hope it helps.