Html table create in javascript

Instant and dynamic HTML table creation with JavaScript

Do you find hard-coding HTML tables tedious? The good news is you can spare yourself this effort by creating tables dynamically using JavaScript.

To start using the table generator function, copy and paste the code below into your project and call the function according to the usage notes.

Build notes that may be helpful to you in creating your own table generator function or customizing the one provided here are contained in notes alongside the code.

Using the JavaScript table generator function

Usage notes

  1. rows : table rows (numeric)
  2. cols : table columns (numeric)
  3. thead : head title (string) or column titles (array)
  4. tfoot : foot title (string)

The return value of the function is the table. So it can be rendered to the DOM like this:

     

Output examples

Example 1: Simple table

A simple table with a heading and five rows of data:

const data = ["United States","China","India","Russia","Germany"]; tableCreate(5,1, "Five large countries", "By JavaScript");

Example 2: Meal plan

A more complex table with multiple rows and columns as well as column titles.

The cells in the first column of the table have the class attribute col-left and so can be separately styled in CSS:

// Define data input const data = ["Monday", "Cereal", "Steamed rice", "Baked Potatoes", "Tuesday", "Bagel", "Spaghetti bolognese", "Pasta salad", "Wednesday", "Oatmeal", "Pasta", "Burger", "Thursday", "Cereal", "Fish and chips", "Fried Rice", "Friday", "Fried breakfast", "Sandwiches", "Lasange" ] // Define headings const headings = ['', 'Breakfast', 'Lunch', 'Dinner'] /* Call tableCreate */ tableCreate(5,4,data,headings,'Created by JavaScript');

The code

Table generator function:

/* Defining the tableCreate function */ function tableCreate(rows, cols, data, thead, tfoot) < // 1) Create table and body elements let table = document.createElement('table') let tableBody = document.createElement('tbody') // 2) Optional header let headContent = document.createElement('thead') let tr = document.createElement('tr') // 2.1) Sets default behavior: Single cell header if (thead && Array.isArray(thead) == false) < let td = document.createElement('td') td.innerHTML = thead // Set header text to argument input td.setAttribute('colspan', cols) // Span header for as many cols as table tr.append(td) headContent.append(tr) // append head row to thead element thead = headContent // Make this final value of thead >// 2.2) If "split" is third argument: Creates a multi-cell header if (Array.isArray(thead)) < let i for (i = 0; i < cols; i++) < let td = document.createElement('td') td.id = 'thead' + i td.innerHTML = thead[i] tr.append(td) // append multiple td to head row >headContent.append(tr) // append head row to thead element thead = headContent // Make this final value of thead > // 3) Optional footer (text is user input string) if (tfoot) < footElement = document.createElement('tfoot') tr = document.createElement('tr') td = document.createElement('td') td.innerHTML = tfoot // Set text to fourth argument input td.setAttribute('colspan', cols) tr.append(td) // Append single cell to row footElement.append(tr) // Append row to tfoot element tfoot = footElement // Make this final value of tfoot >// 4) Create table body rows and cell with loops let i for (i = 0; i < rows; i++) < // Loop to create row let tr = document.createElement('tr') let * cols // Nested loop to append cells to rows (first loop second loop etc) for (j = 0; j < cols; j++) < let td = document.createElement('td') id++ // increase id by 1 (first loop is 0+1 = 1) if (id == i * cols + 1) < td.classList.add('left-col') >td.innerHTML = id // print id in col cell td.setAttribute('id', 'cell' + id) // set id of element to id tr.append(td) // append col cell to table row // Repeats until j < column numbers entered by user if (data) < td.innerHTML = data[id - 1] >> tableBody.append(tr) > // 5) Append head, body and footer if (thead) < table.append(thead) >table.append(tableBody) if (tfoot) < table.append(tfoot) >// Show table in console console.log(table) // 6) Return a value for the function return table >

CSS styling

/* import custom Open Sans font */ @import url(‘https://fonts.googleapis.com/css2?family=Open+Sans&display=swap’); body < background: linear-gradient(#e66465, #9198e5); background-repeat: no-repeat; background-position: top left; height: 100vh; margin: 0px; >#table < display: flex; justify-content: center; margin-top: 3rem; >table < font-family: 'Open Sans', sans-serif; border-collapse: collapse; color: black; >thead < background-color: lightblue; font-weight: bold; border-bottom: 2px solid white; >th, td < padding: 0.5rem; padding-left: 3rem; padding-right: 3rem; text-align: center; >tbody tr td < padding: 0.5rem; padding-left: 0.8rem; padding-right: 0.8rem; >/* Even row styling */ tbody tr:nth-child(even) < background-color: #f2f2f2; >/* Odd row styling */ tbody tr:nth-child(odd) < background-color: white; >/* Left column styling */ .col-left < background-color: lightblue; color: black; font-weight: 400; border-top: 2px solid white; border-bottom: 2px solid white; >tfoot < background-color: rgb(206, 231, 240); font-size: 0.7rem; padding: 0.1rem; border-top: 2px solid white; >tfoot tr td

Источник

Create Table Using JavaScript

Create Table Using JavaScript

  1. Various Tags Used to Create a Table in HTML
  2. Create a Table Using JavaScript

The JavaScript programming language allows us to create and manipulate DOM (Document Object Model) elements. It gives us much more flexibility and makes it a lot easier for everyone to work with DOM, especially if you are a backend developer.

There are two ways of adding HTML elements like tables to an HTML document, the first is by adding the HTML table tag directly into our HTML webpage, and the second way is by creating the entire table inside our JavaScript code. The second option is the most popular way of creating and adding the table to the DOM.

But before diving deep into how the table is created with JavaScript, let’s first visually understand the various table tags used to create a table and what each of those tags exactly means. This will give you a visual representation of the table, making it much easier for you to understand the code part later in this article.

Various Tags Used to Create a Table in HTML

Below is the list of tags that are used to create a table in HTML.

Family tree of Table tag in HTML

  1. table : The table HTML tag represents the entire table in HTML. This is the starting tag of the table inside which all the other tags related to the table (like thead , tr , td , etc) will be used depending upon how you want to structure the table.
  2. thead : The thead stands for table heading. This tag is used to add heading to the tables. It usually represents the first row of the table. To add data inside the thead tag, we use the th tag. If you don’t want to add a heading to your tables, you can skip the thead tag.
  3. tbody : The tbody stands for table body. This tag represents the entire body or contents of the table.
  4. tfoot : The tfoot stands for table footer. It usually represents the last row of the table. This tag is optional. We don’t use this tag that often.
  5. tr : The tr stands for table row. This represents the entire row of the table. To insert data into the table either inside the heading, body, or footer of the table, we first have to create a row, and then inside that row, we can insert the data with the help of the td tag.
  6. th : The th is only used inside the thead tag. It represents the single cell of the heading row. It makes the headings of the table in bold format.
  7. td : The td stands for table data. It represents the single cell of the table. It is similar to th , but the only difference is that th is used only inside the thead tag, and td is used elsewhere. The td tag can be used with the tbody and tfoot tags.

If you combine all of these tags in nested form i.e, one inside another, then this is how the table will look like after it is created.

Visual representation of a table

The red border represents the entire table. Inside this, we have 3 tags, table header ( thead ), table body ( tbody ), and table footer ( tfoot ), which are represented with the green border. To insert data inside these three tags we first have to create a row with the help of the tr tag. This row is represented with the yellow border. And then, to insert data into the table header, we use the th tag, and to insert data within the table body or table footer, we use the td tags. It is shown with the help of grey color.

Create a Table Using JavaScript

To create an HTML element using JavaScript we have to use a method called document.createElement() that takes tag name which is a string as a parameter. For instance, we want to create a table, so we will pass the string table as an input to the createElement() method document.createElement(‘table’) .

The above table has 4 rows. The first row contains all the heading, and the next three rows contain the data.

Below we have the HTML, CSS, and JS code. Inside our body tag, we initially don’t have anything. We will create our table inside the JavaScript, and at the end, we will append the entire table to the body tag so that it will be visible on the webpage. Inside the style tag, we have given some basic styling to our table.

 html lang="en"> head>  meta charset="UTF-8">  meta http-equiv="X-UA-Compatible" content="IE=edge">  meta name="viewport" content="width=device-width, initial-scale=1.0">  title>Documenttitle>   style>  table  border-collapse: collapse;  border-spacing: 0;  >  th, td  padding: 10px 20px;  border: 1px solid #000;  >  style>  head> body id="body">   script src="script.js">script>  body>  html> 

To create a table, we will first create the table tag. Then we will store this tag into a variable table so that later we can use it. In the same way, we will also create thead and tbody tags and store them inside the variables. Then we append thead and tbody to the table tag.

let table = document.createElement('table'); let thead = document.createElement('thead'); let tbody = document.createElement('tbody');  table.appendChild(thead); table.appendChild(tbody);  // Adding the entire table to the body tag  document.getElementById('body').appendChild(table); 

You have to append or add that table that you have created in JavaScript to the body tag. We first have to get the HTML body tag using its id , and then we will append the table using something called the appendChild() method. Since we already have stored our table inside the table variable, we will just have to append the table we created as a child to this body element.

At this point, this is how the structure of our table looks like.

table element img_1

To add rows and data to our table, we will create table rows ( tr ), table heading ( th ), and table data ( td ) tags using the createElement() method, and then we will add the data inside those elements with the help of the innerHTML property.

// Creating and adding data to first row of the table  let row_1 = document.createElement('tr'); let heading_1 = document.createElement('th'); heading_1.innerHTML = "Sr. No."; let heading_2 = document.createElement('th'); heading_2.innerHTML = "Name"; let heading_3 = document.createElement('th'); heading_3.innerHTML = "Company";  row_1.appendChild(heading_1); row_1.appendChild(heading_2); row_1.appendChild(heading_3); thead.appendChild(row_1);  // Creating and adding data to second row of the table  let row_2 = document.createElement('tr'); let row_2_data_1 = document.createElement('td'); row_2_data_1.innerHTML = "1."; let row_2_data_2 = document.createElement('td'); row_2_data_2.innerHTML = "James Clerk"; let row_2_data_3 = document.createElement('td'); row_2_data_3.innerHTML = "Netflix";  row_2.appendChild(row_2_data_1); row_2.appendChild(row_2_data_2); row_2.appendChild(row_2_data_3); tbody.appendChild(row_2);  // Creating and adding data to third row of the table  let row_3 = document.createElement('tr'); let row_3_data_1 = document.createElement('td'); row_3_data_1.innerHTML = "2."; let row_3_data_2 = document.createElement('td'); row_3_data_2.innerHTML = "Adam White"; let row_3_data_3 = document.createElement('td'); row_3_data_3.innerHTML = "Microsoft";  row_3.appendChild(row_3_data_1); row_3.appendChild(row_3_data_2); row_3.appendChild(row_3_data_3); tbody.appendChild(row_3); 

After inserting the data using the innerHTML property, we will append that data to their respective rows. For example, first, we are adding the headings (i.e heading_1 , heading_2 , heading_3 ) to row_1 . And then we are appending our first row, i.e., row_1 , to the thead tag as a child.

Similarly, we are creating another 2 rows i.e row_2 and row_3 and then appending ( row_2_data_1 , row_2_data_2 , row_2_data_3 ) and ( row_3_data_1 , row_3_data_2 , row_3_data_3 ) variables respectively to these 2 rows. And at the end, we are appending these 2 rows to the tbody tag as it’s children’s.

Now, this is how the table and its HTML structure look like in the developer’s console.

table element img_2

At the left, we have the table, and at the right, we have the browser-generated code. You can customize the js code based on how you want the table to look. We have only used 3 JavaScript methods ( createElement() , innerHTML , appendChild() ) in order to achieve this.

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Related Article — JavaScript DOM

Источник

Читайте также:  Блочная вёрстка
Оцените статью