Search code examples
javascripthtmlcsscss-grid

Access dynamically added CSS Grid items from parent grid container in grid order using JavaScript?


I have a CSS Grid Layout with no preset columns or rows because the number of items to be added is unknown beforehand. I use JS to create DOM elements and set their column and row numbers. Later, I want to update specific spots in the grid with a new element; before doing so I want to check if there is an element already at that position in the grid and, if so, retrieve and remove it.

To do that I'm looking for something along the lines of a 'containerElement.getElements().gridOrder()' type of deal which would return children elements in an array (or 2D array).

Perhaps I'm looking in the wrong place but I haven't seen anything like this on MDN. Do I need to loop through child elements and use their 'style.gridColumn' and 'style.gridRow' properties to manually sort things?

Here is sample code showing how I'm dynamically adding items to a grid:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>test page</title>
    
    <style>
    .box {
      width: 30px;
      height: 30px;
      border-radius: 5px;
      background-color: rgb(207,232,220);
      margin: 5px;
    }
    .wrapper {
        display: grid;
        grid-gap: 20px;
        background-color: rgb(79,185,227);
        color: #fff;
        overflow: auto;
    }
    </style>
    
    <script>
     function run(){
     
       let con = document.getElementsByClassName('wrapper')[0];
      
       for(let i=1; i<10; i++){
         let e = document.createElement('div');
         e.className = 'box';
         e.id = i+"";
         e.style.gridColumn = i;
         e.style.gridRow = i;
         con.appendChild(e);
       }
     }
    </script>
  </head>

  <body onLoad='run()'>
    <h1>Grid</h1>
    
    <div class="wrapper">
    </div>
  </body>
</html>

Solution

  • I did not find any further information relating to my question so I went ahead with my own suggestion in the post; I just used a standard 2D array to track which spaces were filled or not.

    Since arrays in JavaScript are dynamic this only requires checking if a slot contains an existing array for a row-- adding one if it doesn't --and then adding the item at the specified location.