I'm creating a jstree in my program. Now I'm able to get the checked node id. But how can I get the id of the parent node id and also the parent's parent node id.
Below is my javascript to get the children node id.
$('#tree-container').on('changed.jstree', function (e, data) {
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).id.trim());
}
//alert('Selected: ' + r.join(', '));
console.log('Selected: ' + r.join(', '));
});
Here is my jsfddle. Please take a look. http://jsfiddle.net/jjfcnho8/2/ When i select Child 9, I can get child 9 id. Then how can I get Child 2 and folder 1 id.
Anyone know please help me. Thank you very much!
You could use the
parents
property of the node object you get fromdata.instance.get_node()
. As several nodes could have the same ancestor, you'd maybe want to avoid gathering duplicates. For this you can use aSet
. This is just one way you could do it:Note that this will include the root node as well, which has id '#'.
Here is the updated fiddle.
Without the root node
To get the list without the
#
, it is the easiest to apply a filter on the result:EcmaScript2015
The above scripts use features from EcmaScript2015 (ES6). Some editors may highlight syntax errors when they are not configured to recognise ES6 syntax. Here you can find how to configure VSCode, Sublime Text, and WebStorm for ES6.
ES5 Alternative
In ES5 you would use an object (
acc
) to collect unique id references as property names. AlthoughObject.keys
is really ES6, it is often supported in otherwise ES5 browsers:Here is the corresponding fiddle.
Circular references in data
You wrote in comments that you tried to do this:
But that data structure has parent and child references in it, so it is possible to go from a child to its parent object, and from there back to its child object, ... which is endless. Such structures cannot be converted to JSON. See this Q&A for solutions.