I had to do something similar (except I was modifying the expanded state). I ended up creating a recursive Javascript function that walked its way up the tree and modified each node.
This works for me:
There's probably a cleaner way to do it with a single jQuery selector.