Looking at the list below, it's a simple one that allows users to add and remove items while also changing their order using buttons. However, I want to enhance this feature by removing the "up" button for the first item and the "down" button for the last item. Initially, everything might seem fine, but in reality, I only took 4 lines of code to make these changes which led to issues when users modified or added new items. I'm sure there are smarter ways to implement this, but I've personally tried an approach that I can't seem to get working after spending over 2 hours on it.
My idea:
FIRST PART: Creating functions to remove the "up" button from the second li
and moving it to the first li
. Also, removing the "down" button from the penultimate li
and relocating it to the last li
.
function upButtonFixer (li1,li2){
var up = document.createElement("BUTTON");
up.className = "up"
up.textContent="up"
li1.appendChild(up);
var upper = li2.getElementsByClassName('up')[0];
li2.removeChild(upper);
}
function downButtonFixer (li1,li2){
var down = document.createElement("BUTTON");
down.className = "down"
down.textContent="down"
li2.appendChild(down);
var downer = li1.getElementsByClassName('down')[0];
li1.removeChild(downer);
}
SECOND PART : Then I called both functions within an if statement as shown below:
ul.addEventListener('click',(event)=>{
if (event.target.tagName == "BUTTON"){
if (event.target.className=="up"){
**if (prevLi == ul.firstElementChild)
upAdderRemover(prevLi,li);**
}
if (event.target.className=="down"){
**if (li==ul.lastElementChild)
downAdderRemover(li,nextLi);**
}
}
... (The remaining HTML, CSS, and JavaScript code has been omitted for brevity) ...