Looping through children can get tricky because you need to go through siblings etc. (tree traversal).

Instead of doing that, you can do the reverse and check if target element or any its ancestors is the toggle element. That way, you only go upwards in the tree and you're guaranteed to stop at the root element.