Properly replace when new nodes are generated

based on @Raynos's recommendation