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
<div id="mainC">
<div > 1 </div>
<div > 2 </div>
<div > 3 </div>
</div>
const cards = document.querySelectorAll(".card");
const firstCard = document.querySelectorAll(".card")[0].innerHTML;
cards[0].remove();
document.getElementById("mainC").appendChild(firstCard);
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
CodePudding user response:
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 > 1 </div>
<div > 2 </div>
<div > 3 </div>
</div>
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 > 1 </div>
<div > 2 </div>
<div > 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 > 1 </div>
<div > 2 </div>
<div > 3 </div>
</div>
CodePudding user response:
you have used document.querySelectorAll(".card")[0].innerHTML which gives '1' which is not type "node" so it will give an error when appending as a child.
remove .innerHTML and it will work
here is an example that removes the first child and append it to the end.
const shuffle = () => {
const parent = document.querySelector("#mainContainer");
const childrens = [...parent.children];
parent.appendChild(childrens.splice(0,1)[0]);
};
<button type="button" onclick=shuffle()> suffel</button>
<div id="mainContainer">
<div >1</div>
<div >2</div>
<div >3</div>
</div>