简体   繁体   中英

How to reorder elements by JavaScript

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>

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>

It may or may not work for your situation, but another possibility is putting them all in a flexbox and using the CSS order property to change the ordering:

<div style="display: flex;">
  <div style="order: -1">1</div> <!-- first -->
  <div style="order: 10">2</div> <!-- last -->
  <div>3</div>
  <div>4</div>
</div>

Then in Javascript you only need to adjust the CSS style's order property to change the ordering dynamically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM