Currently in the process of learning javascript and working on building a simple app. The app consists of an unordered list (ul) with list items (li), each containing two buttons for moving the li up or down.
However, I've encountered an issue where the last item in the list cannot be moved up.
var ul = document.querySelector('ul');
ul.addEventListener('click', (e) => {
let clicked = e.target;
let li= clicked.parentNode;
let next = li.nextElementSibling.nextElementSibling;
let prev = li.previousElementSibling;
if (clicked.className === 'down') {
ul.removeChild(li);
ul.insertBefore(li, next);
} else if (clicked.className === 'up') {
ul.removeChild(li);
ul.insertBefore(li, prev);
}
});
<ul>
<li>item1 <button class="down">Move down</button><button class="up">Move up</button></li>
<li>item2 <button class="down">Move down</button><button class="up">Move up</button></li>
<li>item3 <button class="down">Move down</button><button class="up">Move up</button></li>
<li>item4 <button class="down">Move down</button><button class="up">Move up</button></li>
<li>item5 <button class="down">Move down</button><button class="up">Move up</button></li>
</ul>
Check out my jsfiddle to see the code: https://jsfiddle.net/hu13x8w0/3/
I'm seeking guidance on why it's not functioning correctly in those particular cases. Any help is appreciated!