How to prevent animation only on last child
One option changing a little bit the JS and CSS:
Add a class to the newly added elements to the list
d.className = "added";
Apply the animation only to the
div
that don't have that classmain > div:not(.added) { animation: fade-in 1s; }
The initial div
don't have that class, so they will be animated when the page loads, but the div
that are added later (with the class name you specified) don't have any animation.
Here is a demo on how it would be based on your code:
function addRow(text) {
var d = document.createElement('div');
d.className = "added";
d.innerHTML = text;
var root = document.querySelector('main');
root.appendChild(d);
}
body {
background: #222;
}
main > div {
background: #444;
border: 1px solid green;
}
main > div:not(.added) {
animation: fade-in 1s;
}
div.added:last-child {
background: #999;
}
@keyframes fade-in {
from { opacity: 0 }
to { opacity: 1 }
}
<main>
<div>1</div>
<div>2</div>
<div>3</div>
</main>
<button type="button" onclick="addRow('hello')">Add row</button>