For loops that interact with and manipulate the DOM may look simple, but can be a huge performance buster, depending on what is going on. But let’s look at best practices anyway and write better code.
Original Unoptimized Code
Here is our initial code. This
for loop loops through a bunch of child elements and removes a class, which can trigger a style recalculation. There may be other code in the loop that can cause layout thrashing and style recalculation for each iteration of the loop!
Let’s look at two solutions to git ‘er optimized.
1. removeChild & appendChild
Note that a reference to the removed element must be kept for us to be able to modify and re-insert it later.
2. cloneNode & replaceChild
If we use cloneNode and replaceChild, then we can achieve a similar result. Be warned that cloneNode does not copy any event listeners that may have been added by addEventListener to (I believe any) elements within the clonedNode.