'How to swap 2 Divs in a Container with Javascript

How can I achieve something like this.

I have a Container with

<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>

What I now want to archieve for example: If I have const div1ToSwap = ( div 1 ) const div2ToSwap = ( div 4 )

That the final result will be

<div class="div4">4</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div1">1</div>
<div class="div5">5</div>


Solution 1:[1]

This is a very hacky way to do it, but this way you don't need to remove all elements then append them back in.

let div1 = document.querySelector(".div1");
let div4 = document.querySelector(".div4");
let temp = div1.cloneNode(true);

div1.innerHTML = div4.innerHTML;
div1.className = div4.className;

div4.innerHTML = temp.innerHTML;
div4.className = temp.className;
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>

Solution 2:[2]

it's simple, first you need to container all the div you need to make this script like this, we will write the function later you can try it by the link https://codepen.io/nt0412/pen/rNJWMKP

<div class="all-div-container">
   <div class="div1" onclick="swapDiv(event,this);">
         1
   </div>
   <div class="div2" onclick="swapDiv(event,this);">
         2
   </div>
   <div class="div3" onclick="swapDiv(event,this);">
         3
   </div>
   <div class="div4" onclick="swapDiv(event,this);">
         4
   </div>
   <div class="div5" onclick="swapDiv(event,this);">
         5
   </div>
</div>
<script type="text/javascript">
    function swapDiv(event, elem) {
        elem.parentNode.insertBefore(elem, elem.parentNode.firstChild);
    }
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ahsan
Solution 2 Thuan Nguyen Nam