butiran

mxn divs in div js

· 1 min read · edit

result

code

<div id="container">
</div>

<script>
function createGrid(m, n, s) {
  const rowsRep = "(" + m + ", " + s + ")";
  const colsRep = "(" + n + ", " + s + ")";
  
  const pDiv = document.createElement("div");
  pDiv.style.display = "grid";
  pDiv.style.gridTemplateColumns = "repeat" + colsRep;
  pDiv.style.gridTemplateRows = "repeat" + rowsRep;
  pDiv.style.gap = "4px";
  
  for(let i = 0; i < m; i++) {
    for(let j = 0; j < n; j++) {
      const cDiv = document.createElement("div");
      cDiv.style.width = s;
      cDiv.style.height = s;
      cDiv.style.background = "var(--bg)";
      cDiv.style.border = "1px solid var(--muted-border)";
      cDiv.style.borderRadius = "4px";
      pDiv.append(cDiv);
    }  
  }
  
  return pDiv;
}
</script>

<script>
// get container element, set style
let cnt = document.getElementById("container");
cnt.style.marginTop = "1em";

// create grid element
let grid = createGrid(3, 4, "20px");

// append element to container
cnt.append(grid);
</script>

steps

  1. Open a plain text editor, e.g. vim, nano, Notepad++, VS Code.
  2. Copy and paste code given above.
  3. Save with new name, e.g. jstu-10-mxn-divs-in-div.html.
  4. View using an internet browser, e.g. Google Chrome, Mozilla Firefox, Apple Safari.
  5. Edit HTML file for further modification.
  6. Save the changes
  7. Refresh internet browser to see updated result.
  8. Repeat the previous three steps (5-7).
  9. Close the internet browser.
  10. Close the plain text editor.