What you are describing is actually a configurable setting of the tree. It's just that the default action is set to select the parent node.
From the docs of jstree:
This option specifies the behavior of the tree when a parent of a selected node is closed. The options are
"select_parent"- which deselects the selected node and selects the closed one (similar to windows explorer),
"deselect"- only deselects the selected node or
false- does nothing.
So if you were to set it to deselect, it will simply deselect the node and your end result would be no selection.
With the option set to false, the selected node will remain selected. So when you close the branch, no parent will be selected, and when opened again that last selected node will still be selected.
$.tree.reference("#tree21227695007289061372").settings.ui.selected_parent_close = false
If you were to give your tree region a static ID you could make the tree selection a bit easier by using this selector:
Thank you this works for me in this situation and my problem is solved.
But I think Apex should be improved sligthly on this issue.
If I leave the default mode when I close the tree the root node becomes selected , when I then expand the node the root action stays selected.
OK this is the default mode.
Visually everything seems OK but there is an item which contains the selected node.
If I do F5 the selected node changes again back to the child leaf. (Since the ITEM holding the selection ID was not updated. )
This is because collapsing and expanding the tree does not trigger a change on the item.
I tried with my real page and the process that saves the selected node is saving the child leaf which is not selected visually.
I think in future this type of functionality could be in Apex with an easy selection option otherwise tree looks like a patched in functionality.
But maybe I am wrong.
Thank you anyway.