To clear and rebuild a jsTree, you'll need to remove all existing nodes from the tree and then add new nodes to it. You can achieve this by using jsTree's built-in methods and API. Below is an example of how to clear and rebuild a jsTree:

Assuming you already have a jsTree initialized on an HTML element with the ID "jsTree":

html
<!-- HTML element to initialize the jsTree --> <div id="jsTree"></div>

JavaScript code to clear and rebuild the jsTree:

javascript
// Sample data for the new tree structure const newData = [ { id: 'node1', text: 'Node 1' }, { id: 'node2', text: 'Node 2', children: [{ id: 'node21', text: 'Node 2.1' }] }, { id: 'node3', text: 'Node 3' }, ]; // Function to clear and rebuild the jsTree function rebuildTree() { // Get the jsTree instance const jsTree = $('#jsTree').jstree(true); // Clear the existing tree (remove all nodes) jsTree.delete_node(jsTree.get_node('#').children); // Rebuild the tree with new data jsTree.create_node('#', newData); } // Initialize the jsTree with some initial data (optional) $('#jsTree').jstree({ core: { data: [ { id: 'nodeA', text: 'Node A' }, { id: 'nodeB', text: 'Node B', children: [{ id: 'nodeB1', text: 'Node B.1' }] }, { id: 'nodeC', text: 'Node C' }, ], }, }); // Call the function to clear and rebuild the tree (e.g., on a button click) // Note: Make sure to call this function when you want to rebuild the tree with new data. rebuildTree();

In this example, the rebuildTree function clears the existing tree by removing all nodes and then rebuilds it with new data defined in the newData array. You can call this function whenever you want to rebuild the tree with new data.

Keep in mind that jsTree's API is flexible, and you can customize the tree's behavior and appearance based on your specific use case and requirements.

Have questions or queries?
Get in Touch