How to get all nodes present in jsTree?
I am building jsTree with xml
Root
-----A
-----A1
-----A1.1
-----A1.2
-----A2
-----`A2.1`
-----A2.2
-----B
-----B1
-----B2
-----C
-----C1
-----C1.1
-----C2.2
I want array of all nodes(ID) present in jsTree is as follows
Expected output: [Root, A, A1, A1.1, A1.2, A2, A2.1, A2.2, B, B1, B2, C, C1, C1.1, C2.2]
I needed the same thing and came up with the below solution given that get_xml is no longer available in jstree3
function get_jstree_order(root_ul_selector, children) {
var output = [];
var _this = this;
if (typeof children === 'undefined') {
children = $(root_ul_selector).find('> li');
}
children.each(function() {
if ($(this).find('ul').length > 0) {
output.push({
id: $(this).attr('id'),
children: get_jstree_order(root_ul_selector, $(this).find('ul > li'))
});
return;
}
output.push({
id: $(this).attr('id'),
children: false
})
});
return output;
}
console.log(get_jstree_order('#mytree > ul'));
Outputs (converted to JSON for readability):
[
{
"id": "1",
"children": false
},
{
"id": "2",
"children": false
},
{
"id": "5",
"children": [
{
"id": "6",
"children": false
},
{
"id": "7",
"children": false
}
]
},
{
"id": "8",
"children": false
},
{
"id": "9",
"children": false
},
{
"id": "10",
"children": false
},
{
"id": "11",
"children": false
}
]
Modify as needed; to include whats need, but my purpose served only to get the correct order of items for server side processing.
It's fine when lazy loading provided children id's are independent of their parents (eg, the first child of a parent always starts at 1)
You can traverse each node element and put it's id in an array via:
var idList = [];
var jsonNodes = $('#tree').jstree(true).get_json('#', { flat: true });
$.each(jsonNodes, function (i, val) {
idList.push($(val).attr('id'));
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With