Search code examples
javascripthtmldomnodelist

changing Div order in a div main container, javascript DOM manipulation


i want to move a div form the start to the end in a the same div:from 1-2-3 to 2-3-1

my code

const cards = document.querySelectorAll(".card");
const firstCard = document.querySelectorAll(".card")[0].innerHTML;
cards[0].remove();
document.getElementById("mainC").appendChild(firstCard);
<div id="mainC">
 <div class="card"> 1 </div>
 <div class="card"> 2 </div>
 <div class="card"> 3 </div>
</div>

i want to move a div form the start to the end in a the same div:from 1-2-3 to 2-3-1


Solution

  • Based on your original code,we need to remove .innerHTML,then it will work

    const cards = document.querySelectorAll(".card");
    const firstCard = document.querySelectorAll(".card")[0];// remove .innerHTML and it will work
    cards[0].remove();
    document.getElementById("mainC").appendChild(firstCard);
    <div id="mainC">
     <div class="card"> 1 </div>
     <div class="card"> 2 </div>
     <div class="card"> 3 </div>
    </div>

    Another solution is to store the content into an array and change the array element order

    let divs = []
    document.querySelectorAll('#mainC .card').forEach(d =>{
      divs.push(d.outerHTML)
    })
    divs.push(divs.shift())
    document.querySelector('#mainC').innerHTML = divs.join('')
    <div id="mainC">
     <div class="card"> 1 </div>
     <div class="card"> 2 </div>
     <div class="card"> 3 </div>
    </div>