Easily Generate a Horizontal Table with JavaScript
Tags: webdev, javascript, tutorial, beginners
Published: 2022-06-03 08:31:13

I will show you how to generate a table using a function in JavaScript.

## STEP 1

Let us declare the table data we need for our table.

### theadData

This Object holds the columns needed for the table head.

We will add a new property **{ "1" }** with its value as an array **["name", "text-danger"]**.
Now, the first index of the array is the **column** needed for the table head, and the second index is the ***css class*** of that column.

### tbodyData

This Object holds the columns needed for the table body.

The structure is almost the same as the one above, except that you will have to add more values depending on the table head columns.

### tableClass

This variable holds the ClassList of our table. You can separate multiple classes with a space.

```javascript
const theadData = {
"1" : ["name","text-danger"],
"2" : ["email", "text-danger"],
"3" : ["password", "text-danger"]
};
const tbodyData = {
"1": ['Simon Ugorji', 'up@us.com', 'simon'],
"2": ['John Doe', 'johnny@doe.com', 'john'],
"3": ['Cherish Junior', 'cherish@junior.com', 'cherish']
};
const tableClass = "table";

```

## STEP 2

Let us create a function to generate a table with the data we have provided.

In our function, we need to specify a local variable **( t )** which we will use within a loop.

Now we will use **document.createElement()**, to create the elements needed within our table.

```javascript
(function generateTable() {
    //increment
    var t;
    //create table with classlist
    var table = document.createElement("table");
    table.setAttribute("class", tableClass);
    //create table head
    var thead = document.createElement("thead");
    //create table head table row
    var theadTr = document.createElement("tr");
})();
```

Now we need to loop through the table head data provided in the variable **(theadData)** and append each data inside our table head. We will use the **( t )** variable we created earlier for this.

Our loop will check the length of the *thead* data provided, then it will access its properties and values, and create a table row with a single table data from our loop, inside of it.

Inside the loop, we will use the method **appendChild()** to append all elements found within table head > table row to its parent which is table row.

After the loop must have finished, we will append the table row to its parent element which is table head **(thead)**.

```javascript
(function generateTable() {
    //increment
    var t;
    //create table with classlist
    var table = document.createElement("table");
    table.setAttribute("class", tableClass);
    //create table head
    var thead = document.createElement("thead");
    //create table head table row
    var theadTr = document.createElement("tr");
    //Loop through the table head dataset provided
    for(t = 1; t <= Object.keys(theadData).length; t++){
	    //create table head > table row >  table data
	    var td = document.createElement("td");
	    //set inner text to be a single value from the loop
	    td.innerText = theadData[t][0];
	    //set class
	    td.setAttribute("class", theadData[t][1]);
	    //append each of the table data to the thead row
	    theadTr.appendChild(td);
    }
    //append thead row to thead
    thead.appendChild(theadTr);
})();
```

### NOTE

I used **Object.keys(theadData).length** to retrieve the length of our **theadData** Object. This is a known method of accessing the length of an object.

So far our HTML table structure should Look like this

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640130159291/wqFm2Rbyq.png)

## STEP 3

Let us use the same process for the table body but a bit differently.

> The reason why the **table head** above, was so easy to complete, is because in a horizontal table, **table heads** contain a max of one row for all columns.

This is unlike the table body, where you will need to check the number of records provided before you can create the row for that data.

Just like the image below, we have 2 rows specifying 2 different records. So we have to check properly, the number of records that we are dealing with, then create a row for each record.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640130411028/o8gWrUvjb.png)

```javascript
(function generateTable() {
    //increment
    var t;
    //create table with classlist
    var table = document.createElement("table");
    table.setAttribute("class", tableClass);
    //create table head
    var thead = document.createElement("thead");
    //create table head table row
    var theadTr = document.createElement("tr");
    //Loop through the table head dataset provided
    for(t = 1; t <= Object.keys(theadData).length; t++){
	    //create table head > table row >  table data
	    var td = document.createElement("td");
	    //set inner text to be a single value from the loop
	    td.innerText = theadData[t][0];
	    //set class
	    td.setAttribute("class", theadData[t][1]);
	    //append each of the table data to the thead row
	    theadTr.appendChild(td);
    }
    //append thead row to thead
    thead.appendChild(theadTr);
    /**** TBODY ****/
    var tbody = document.createElement("tbody");
    //Init table body object
    var tbodyTd =  {};
    //create table body table data
    var td; 
    //loop through the table body dataset provided -> Number of records
    for(t = 1; t <= Object.keys(tbodyData).length; t++){
	    //for each record, create a table row
        var tbodyTr = document.createElement("tr");
    }
})();
```
## STEP 4

Now inside the second loop, we need another loop within it, that will go through the records again, to append the values of each property to the element **table body > table data (td)**.

If you noticed, I created a new object **( var tbodyTd =  {} )** that will hold all elements **table data( td )** needed for table body > table row **(tr)**.

So still inside this loop, we will create the table data **td** element and then store it in the object **( tbodyTd )**. Since we can refer to a property in this object as a *Node*, we can directly append our value to this property using the method **.innerText()**, and then append that property to table body > table row.

```javascript
(function generateTable() {
    //increment
    var t;
    //create table with classlist
    var table = document.createElement("table");
    table.setAttribute("class", tableClass);
    //create table head
    var thead = document.createElement("thead");
    //create table head table row
    var theadTr = document.createElement("tr");
    //Loop through the table head dataset provided
    for(t = 1; t <= Object.keys(theadData).length; t++){
	    //create table head > table row >  table data
	    var td = document.createElement("td");
	    //set inner text to be a single value from the loop
	    td.innerText = theadData[t][0];
	    //set class
	    td.setAttribute("class", theadData[t][1]);
	    //append each of the table data to the thead row
	    theadTr.appendChild(td);
    }
    //append thead row to thead
    thead.appendChild(theadTr);
    /**** TBODY ****/
    var tbody = document.createElement("tbody");
    //Init table body object
    var tbodyTd =  {};
    //create table body table data
    var td; 
    //loop through the table body dataset provided -> Number of records
    for(t = 1; t <= Object.keys(tbodyData).length; t++){
	    //for each record, create a table row
        var tbodyTr = document.createElement("tr");
        //loop through the dataset again to create all table data that we need
        for(var a = 0; a < Object.keys(tbodyData[t]).length; ++a){
    	    //add a new table data property to the table body object
       	    tbodyTd[a]  = document.createElement("td");
	   	    // set the inner text of the table data within our object
       	    tbodyTd[a].innerText = tbodyData[t][a];
    	    //append single table data to table row
		    tbodyTr.appendChild(tbodyTd[a]);
        }
        //after table data set loop, to create the table data we need,
        //append that data to table body table row	
        tbody.appendChild(tbodyTr);
    }
})();
```

After this loop, we will then append all elements found inside table body > table row to table body.

## LAST STEP

We have succeeded in creating the table elements below;

- table > thead > tr > td
- table > tbody > tr > td

Now it's time to append thead and tbody to our table and then provide the element we should append our table into.

```javascript
(function generateTable() {
    //increment
    var t;
    //create table with classlist
    var table = document.createElement("table");
    table.setAttribute("class", tableClass);
    //create table head
    var thead = document.createElement("thead");
    //create table head table row
    var theadTr = document.createElement("tr");
    //Loop through the table head dataset provided
    for(t = 1; t <= Object.keys(theadData).length; t++){
	    //create table head > table row >  table data
	    var td = document.createElement("td");
	    //set inner text to be a single value from the loop
	    td.innerText = theadData[t][0];
	    //set class
	    td.setAttribute("class", theadData[t][1]);
	    //append each of the table data to the thead row
	    theadTr.appendChild(td);
    }
    //append thead row to thead
    thead.appendChild(theadTr);
    /**** TBODY ****/
    var tbody = document.createElement("tbody");
    //Init table body object
    var tbodyTd =  {};
    //create table body table data
    var td; 
    //loop through the table body dataset provided -> Number of records
    for(t = 1; t <= Object.keys(tbodyData).length; t++){
	    //for each record, create a table row
        var tbodyTr = document.createElement("tr");
        //loop through the dataset again to create all table data that we need
        for(var a = 0; a < Object.keys(tbodyData[t]).length; ++a){
    	    //add a new table data property to the table body object
       	    tbodyTd[a]  = document.createElement("td");
	   	    // set the inner text of the table data within our object
       	    tbodyTd[a].innerText = tbodyData[t][a];
    	    //append single table data to table row
		    tbodyTr.appendChild(tbodyTd[a]);
        }
        //after table data set loop, to create the table data we need,
        //append that data to table body table row	
        tbody.appendChild(tbodyTr);
    }
    //append table head to table
    table.appendChild(thead);
    //append table body to table
    table.appendChild(tbody);
    document.querySelector('#table').appendChild(table);
})();
```

We have successfully created our Horizontal Table Generator!

Let us test it out in our console with the sample data below.

Before we can be able to append our table, we need to create an element with the id **( 'table' )**.

I will copy the code below and paste it directly on the console of a blank page where I had created an element with the id **( 'table' )**.

```javascript
const theadData = {
"1" : ["Name","text-danger"],
"2" : ["Category", "text-danger"],
"3" : ["Years", "text-danger"]
};
const tbodyData = {
"1": ['Simon Ugorji', 'Web Developer', '2'],
"2": ['John Doe', 'App Developer', '3'],
"3": ['Cherish Junior', 'Full Stack Developer', '4']
};
const tableClass = "table";

(function generateTable() {
    //increment
    var t;
    //create table with classlist
    var table = document.createElement("table");
    table.setAttribute("class", tableClass);
    //create table head
    var thead = document.createElement("thead");
    //create table head table row
    var theadTr = document.createElement("tr");
    //Loop through the table head dataset provided
    for(t = 1; t <= Object.keys(theadData).length; t++){
	    //create table head > table row >  table data
	    var td = document.createElement("td");
	    //set inner text to be a single value from the loop
	    td.innerText = theadData[t][0];
	    //set class
	    td.setAttribute("class", theadData[t][1]);
	    //append each of the table data to the thead row
	    theadTr.appendChild(td);
    }
    //append thead row to thead
    thead.appendChild(theadTr);
    /**** TBODY ****/
    var tbody = document.createElement("tbody");
    //Init table body object
    var tbodyTd =  {};
    //create table body table data
    var td; 
    //loop through the table body dataset provided -> Number of records
    for(t = 1; t <= Object.keys(tbodyData).length; t++){
	    //for each record, create a table row
        var tbodyTr = document.createElement("tr");
        //loop through the dataset again to create all table data that we need
        for(var a = 0; a < Object.keys(tbodyData[t]).length; ++a){
    	    //add a new table data property to the table body object
       	    tbodyTd[a]  = document.createElement("td");
	   	    // set the inner text of the table data within our object
       	    tbodyTd[a].innerText = tbodyData[t][a];
    	    //append single table data to table row
		    tbodyTr.appendChild(tbodyTd[a]);
        }
        //after table data set loop, to create the table data we need,
        //append that data to table body table row	
        tbody.appendChild(tbodyTr);
    }
    //append table head to table
    table.appendChild(thead);
    //append table body to table
    table.appendChild(tbody);
    document.querySelector('#table').appendChild(table);
})();
```
Ah-ha! Just like I expected

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640134133210/T1aFd5kgb.png)

> NOTE: I had styled my table on the blank page. You will see a different design when you run yours.

Go ahead and tweak the function to suit your project.

[If you would like to implement a search form on this table, then this article is for you.](https://dev.to/ugorji_simon/how-to-search-through-a-table-with-javascript-3lg6)

You have reached the end of my article.

## EXTRA

I recently launched a JavaScript package that validates your HTML forms using validation rules, regular expressions, and form input attributes.

I will appreciate it if you spared a few seconds to check it out.

{% embed https://www.producthunt.com/posts/octavalidate %}

Thank You