Iterate over a copy of the parents container since we are removing elements from the original

Fixes #4208.