Function for creating HTML tables in JavaScript

Let's now make a function createTable that will create a table of the given size and add it to the end of the given element.

Let our function take the number of rows as the first parameter, the number of columns as the second parameter, and a reference to the DOM element in which our table will be created as the third parameter.

Let's see how we will use the described function when it is created. Let, for example, we have such a div:

<div id="elem"></div>

Let's make a 3 by 4 table inside this div:

let div = document.querySelector('#elem'); createTable(3, 4, div);

Let now we have two divs:

<div id="elem1"></div> <div id="elem2"></div>

Let's make own table in each of these divs:

let div1 = document.querySelector('#elem1'); createTable(3, 4, div1); let div2 = document.querySelector('#elem2'); createTable(5, 6, div2);

In order for the created tables to be immediately visible, you can add some CSS, for example, this:

td { width: 50px; height: 50px; border: 1px solid black; }

Here is a blank for the described function:

function createTable(rows, cols, parent) { let table = document.createElement('table'); // here we'll create a table with rows (rows) and columns (cols) for () { for () { } } parent.appendChild(table); }

Add the code for the above function blank. Test the finished function.

enru