'Change the on-grid position of an element with javascript

My code is the following :

<!DOCTYPE html>
<html>

<style>
#1 { grid-area: 1; }
#2 { grid-area: 2; }

.grid-container {
  display: grid;
  grid-gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}

.grid-container > div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
</style>

<div class="grid-container">
  <button id="1" onclick="myFunction('1')">1</button>
  <button id="2" onclick="myFunction('2')">2</button>
</div>

<script>

  function myFunction(id) 
    {
       
        if(document.getElementById(id).style.grid-area != "1")
         {

              document.getElementById(id).style.grid-area = "1";

              if(id == 1)
              {

                  document.getElementById("2").style.grid-area = "2";

              }

              else
              {
         
                  document.getElementById("1").style.grid-area = "2";
          
              }

         }

    }

</script>

</html>

I'm looking to change the position of a button on click to occupy the top position on the grid (swapping with the other button if the latter was the one initially on top). I learned that the position is determined by the CSS property "grid-area" but the problem is that it can't be accessed via javascript as it would seem. So, is there a way to achieve the same purpose?



Solution 1:[1]

a bit late, hope you will find it usfull:

Getting grid coordinates:

let btn = document.getElementById("1")
let x = btn.style.gridColumn
let y = btn.style.gridRow

Setting grid coordinates:

let btn=document.getElementById("2")
btn.style.gridColumn = x
btn.style.gridRow = y

replacing buttons entire grid area

If your button takes more than a single grid segment you can use gridArea like so:

let btn1=document.getElementById("1")
let btn2=document.getElementById("2")
btn2.style.gridArea = btn1.style.gridArea 

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 lior bakalo