cteate grid in javascript

To create a grid dynamically in JavaScript, first, we need to create a table element and its child tr and td elements using the DOM manipulation techniques. Here's an example code snippet that generates a 10 x 10 grid.

index.tsx
// Create a table element
const table = document.createElement('table');

// Create rows and columns
for(let i = 0; i < 10; i++) {
  const row = document.createElement('tr');
  for(let j = 0; j < 10; j++) {
     const cell = document.createElement('td');
     row.appendChild(cell);
  }
  // Append row to table
  table.appendChild(row);
}

// Add styles to table and cells
table.style.border = '1px solid black';
table.style.borderCollapse = 'collapse';
Array.from(table.querySelectorAll('td')).forEach(cell => {
  cell.style.border = '1px solid black';
  cell.style.width = '20px';
  cell.style.height = '20px';
});

// Add table to DOM
document.body.appendChild(table);
673 chars
26 lines

In this code snippet, we are creating a table element, then two nested loops that create tr and td elements dynamically. Finally, we are appending the cells under the rows and the rows under the table.

We can further customize the cells' style using CSS, like background color, font size, etc. The generated grid is a simple representation of how to build a grid in JavaScript dynamically.

gistlibby LogSnag