Why is my animation “replayed” when an element is added via innerHTML?
I have a little script that adds a div named “doge” using
innerHTML when clicking on a button on my page, and on this page there’s a div with a CSS keyframes animation.
However, when I click on the button to add the div named “doge” on my page, the CSS animation is “replayed”. Why? How can I fix that?
It’s because you’re modifying all of the element’s HTML when you modify the
According to MDN:
.innerHTML- Removes all of element’s children, parses the content string and assigns the resulting nodes as children of the element.
In doing so, the DOM assumes that the
.myDiv element has just been added which means that the animation is going to be replayed. To work around that, use the
.appendChild() method instead: