Let’s say I got 6 divs, and their current order is 1 to 6, how do I reorder them to make it become 612345?
I’ve tried to store them into a variable and use getElementsByClassName, then use the slice method and the insertAdjacentElement method but it couldn’t work…
const btn = document.querySelector('.reorder');
const elm = document.getElementsByClassName('items');
const lastIndexOfElm = elm.length -1
function reorder() {
let newElm = [...elm].slice(0, lastIndexOfElm);
elm[lastIndexOfElm].insertAdjacentElement('afterend', newElm);
}
btn.addEventListener('click', reorder)
<button class="reorder">Reorder</button>
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
>Solution :
if you want to move the last item of ".items" to the first item, this code may help you.
const btn = document.querySelector('.reorder');
const elm = document.getElementsByClassName('items');
const lastIndexOfElm = elm.length -1
function reorder() {
let lastElm = elm[lastIndexOfElm];
elm[lastIndexOfElm].remove();
document.body.insertBefore(lastElm, elm[0]);
}
btn.addEventListener('click', reorder)
<button class="reorder">Reorder</button>
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>