Анимация может быть достигнута с помощью CSS, если мы добавляем элемент.
В случае удаления нам нужно сначала добавить класс перед удалением, чтобы запустить анимацию, а затем удалить элемент из DOM, когда анимация будет завершена. В примере есть та же самая задержка в 500 м, конечно, это можно сделать, также проверив событие animationEnd в js.
$add = document.getElementById('add');
$remove = document.getElementById('remove');
$parent = document.getElementById('parent');
let i = 0
$add.onclick = function(){
let el = document.createElement("DIV");
el.className='test';
let text = document.createTextNode("Hello "+ i );
el.appendChild(text);
$parent.insertBefore(el, $parent.firstElementChild);
i++;
}
remove.onclick = function(){
$parent.firstElementChild.className += ' remove-animation';
setTimeout(() => {
$parent.removeChild($parent.firstElementChild);
}, 500)
}
.test {
max-height: auto;
animation: test-animation 0.5s;
transition: max-height 0.5s;
margin-bottom: 5px;
overflow: hidden;
}
.remove-animation {
animation: remove-animation 0.5s;
}
@keyframes test-animation {
0% { max-height: 0; }
100% { max-height: 25px }
}
@keyframes remove-animation {
0% { max-height: 25px; }
100% { max-height: 0 }
}
<button id="add" onclick="myFunction()">Add child on top</button>
<button id="remove" onclick="removeChlid()">remove child on top</button>
<div id="parent">
</div>