I get stuck on this challenge so I need help.
A website needs a list where users can rank their favorite foods. Write the setup function, which should register click handlers on all Up! and Down! buttons. The Up! button should move the list item one place up in the list, while Down! button should move the list item one place down in the list.
For example, consider this code:
document.body.innerHTML = `<ol>
<li><button>Up!</button>Taco<button>Down!</button></li>
<li><button>Up!</button>Pizza<button>Down!</button></li>
<li><button>Up!</button>Eggs<button>Down!</button></li>
</ol>`;
setup();
If the button Up! button in Pizza list item is clicked, Pizza should be the first item in the list, while Taco should be the second item.
This is my current code:
function setup() {
let list = document.getElementByTagName('li');
let btnList = document.getElementByTagName('button');
let up;
let down;
for (let l = 0; l < list.length; l++){
for (let b = 0; b< btnList.length; b++){
btnList[b].addEventListener("click", (item, index)=>{
if(btnList[b].textContent == "Up!"){
up = list[l - 1]
} else if(btnList[b].textContent == "Down!"){
down = list[l + 1]
} else{
return list
}
})
}
}
return list;
})
}
}
I need to solve it without jQuery.
You don't need two for loops to iterate over the list elements and the buttons. You only need the buttons, the
lielements are theirparentNodes.Moving up
Once you add the event listeners to every button, you can check if they are up or down buttons by checking their
textContent. If it's an "up" button, you will need to check if it's the first element in the list. If it is, don't do anything, you can't move it any higher. :)If it's not the first element, you can use
insertBeforeto swap nodes. Its first parameter is the node you want to insert, in this case theparentelement;li. The second parameter is the reference; the node before which theliis inserted. That's thepreviousElementSiblingof theparent.Moving down
To move an element down is pretty similar. You probably think that you will use
insertAfterto swap, but there is noinsertAftermethod. You can useinsertBeforeagain, but this time the node you insert will be thenextElementSiblingand the reference is theparent.Check out the snippet below:
You could also just add a single event listener on the
olelement and check if the click target is abutton. You can useevent.target.tagNamefor this. If thetagNameisBUTTON(always uppercase in HTML), you just return to exit early: