I’m trying to figure out how to make a button go to the bottom of the list by clicking on it in JavaScript. I’m a bit of a noob and I didn’t find anything regarding buttons swapping positions.
For example if I click on BTN2
I want the order to be: BTN1
, BTN3
, BTN4
, BTN2
So far I don’t know how to even begin.
<div class="container">
<div class="attp">
<p class="textbox">ATTP</p>
<ul>
<li><button>BTN1</button></li>
<li><button>BTN2</button></li>
<li><button>BTN3</button></li>
<li><button>BTN4</button></li>
</ul>
</div>
</div>
2
Answers
To do what you require you need to attach an event handler to each button. From there you can retrieve the closest
li
element to the button which was clicked, then move it to the bottom of theul
that contains it by callingappend()
. Here’s a working example:As you’re new to JS here’s some required reading on the functions being used here, as you will need to understand their purpose and usage:
Use
Element.closest()
andElement.append()
methods:The above will also work for dynamically generated LI elements since the event is delegated from the parent UL and searches for the button using the
Event.target.closest()
.Refer to: MDN web docs