How can I access a grid of DIV I have created in HTML

Viewed 482

I am stuck since long for I am unable to access the grid of DIVs via rows and columns. I thought I could access them like gridContainer[row][col] and set some property to it. Error in console says "Uncaught TypeError: Cannot read property '0' of undefined at HomeScript.js:25". Attaching the code snippet below for your reference. Any suggestions would be highly appreciated.

    function genDivs (rows, cols) {
  var e = document.getElementById("gridContainer");
  for (var r = 0; r < rows; r++) {
    var row = document.createElement("div");
    row.className = "row";
    for (var c = 0; c < cols; c++) {
      var cell = document.createElement("div");
      if (r == 10 && c == 20)
        cell.className = "gridsquare begin";
      else if (r == 10 && c == 40)
        cell.className = "gridsquare end";
      else
        cell.className = "gridsquare";
      row.appendChild(cell);
    }
    e.appendChild(row);
  }
}


var gridContainer = document.getElementById("gridContainer");
// gridContainer[0][0].style.backgroundColor = "pink"; (want something like this)
var gridCols = 60;
var gridRows = Math.floor(screen.height / 25) - 2;
gridContainer.style.left = ((screen.width - 25 * gridCols) / screen.width) * 50 + "%";

console.log(((screen.width - 25 * gridCols) / screen.width) * 50);
genDivs(20, 20);
<!DOCTYPE html>
<html>

<head>
  <style>
    #gridContainer {
      outline: 1px solid rgb(175, 216, 248);
      font-size: 0;
      position: absolute;
    }

    .row {}

    .gridsquare {
      width: 25px;
      height: 25px;
      box-shadow: 0 1px 0 rgb(175, 216, 248) inset, 1px 0px 0px rgb(175, 216, 248) inset;
      display: inline-block;
    }

    .begin {
      background-color: purple;
    }

    .end {
      background-color: magenta;
    }
  </style>
</head>

<body>
  <div id="gridContainer"></div>
  <script type="text/javascript" src="HomeScript.js"></script>
</body>

</html>

2 Answers

you can use JS querySelector, if you want to access 3 div in the first row use the below syntax

let square = document.querySelector(".row:nth-child(1) .gridsquare:nth-child(3)");
square.style.background = '#000';

You are trying to access grid container as a JS object which it isn't, you can do something like this

const getRow = grid => index => {
  if (grid) {
    return grid.querySelector(`div.row:nth-child(${index + 1})`);
  }
  // handle your exception here
};

const getColumn = grid => (rowIndex, cellIndex) => {
  const row = getRow(grid)(rowIndex);
  if (row) {
    return row.querySelector(`div:nth-child(${cellIndex + 1})`);
  }
// Handle your exception here.
};

getColumn(gridContainer)(0, 0).style.backgroundColor = 'pink';
Related