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?

function addHtml() {
  document.getElementById("wow").innerHTML += '<div class="doge">such wow</div>';
}
@keyframes color {
  10% {
    background: #4CAF50;
  }
  50% {
    background: #3F51B5;
  }
  100% {
    background: #009688;
  }
}

.myDiv {
  background: #000;
  color: #fff;
  animation: color 1s;
}

.doge {
  background: #F57F17;
}
<div id="wow">
  <div class="myDiv">Hi!</div>
  <br>
  <button onclick="addHtml()">Add HTML!</button>
</div>

JSFiddle


solution

It’s because you’re modifying all of the element’s HTML when you modify the .innerHTML property.

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:

Updated Example

var div = document.createElement('div');
div.textContent = 'such wow';
div.className += 'doge';
document.getElementById("wow").appendChild(div);

Alternatively, as Teemu points out, you can also use the .insertAdjacentHTML() method:

Updated Example

document.getElementById("wow").insertAdjacentHTML('afterend', '<div class="doge">such wow</div>');