Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Create Table From Array In Javascript

Tags: table html array

INTRODUCTION
DYNAMIC TABLES

Welcome to a beginner’s tutorial on how to create a Table from an array with Javascript. Need to generate a dynamic table from an array of data in Javascript? Yes, you can, and it is actually pretty easy. This guide will walk you through 2 different ways to do it, read on to find out!

I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
Traditional Way

Section B
Object-Oriented Way

Extra
Download & More

Closing
What’s Next?

 

SECTION A
THE TRADITIONAL WAY

Let us start with the more traditional way of creating dynamic tables in Javascript.

THE HTML

array-table.html


  
    
      Javascript array to table
    

There is nothing much on the HTML side, all you need is to just create a container 

 to put the table into.

THE JAVASCRIPT

1-traditional.js
window.addEventListener("load", function(){
  // LET'S SAY THAT WE HAVE A SIMPLE FLAT ARRAY
  var data = ["doge", "cate", "birb", "doggo", "moon moon", "awkward seal"];

  // DRAW THE HTML TABLE
  var perrow = 3, // 3 items per row
      html = "";

  // Loop through array and add table cells
  for (var i=0; i" + data[i] + "";
    // Break into next row
    var next = i+1;
    if (next%perrow==0 && next!=data.length) {
      html += "";
    }
  }
  html += "
"; // ATTACH HTML TO CONTAINER document.getElementById("container").innerHTML = html; });

Yep, “converting” an array to a table is as easy as that.

  • First, we need to have an array. Which I prefer to keep simple, and just a “flat array” that we can loop through easily.
  • Next, we define a string var html to hold the HTML for the , and define var perrow to limit the number of cells per row.
  • Loop through the array, add the table cells
  •  to var html.
  • Finally, we put the complete HTML string into the container, and that’s all to it!
  • SECTION B
    OBJECT-ORIENTED METHOD

    Moving on, we will walk through a slightly more “modern” object-oriented way to build tables.

    THE JAVASCRIPT

    2-create-element.js
    window.addEventListener("load", function(){
      // LET'S SAY THAT WE HAVE A SIMPLE FLAT ARRAY
      var data = ["doge", "cate", "birb", "doggo", "moon moon", "awkward seal"];
    
      // DRAW HTML TABLE
      var perrow = 3, // 3 items per row
          count = 0, // Flag for current cell
          table = document.createElement("table"),
          row = table.insertRow();
    
      for (var i of data) {
        var cell = row.insertCell();
        cell.innerHTML = i;
    
        // You can also attach a click listener if you want
        cell.addEventListener("click", function(){
          alert("FOO!");
        });
    
        // Break into next row
        count++;
        if (count%perrow==0) {
          row = table.insertRow();
        }
      }
    
      // ATTACH TABLE TO CONTAINER
      document.getElementById("container").appendChild(table);
    });

    The working principals behind this version are actually the same as the traditional method. But instead of “manually writing” HTML, we create DOM (Document Object Model) objects:

    • Define your array of data.
    • Create a table object.
    • Create a new row for the table.
    • Loop through the array, append cells to the row.
    • Break up and add new rows where necessary.
    • Finally, append the table object into the container.

    WHICH ONE SHOULD WE USE?

    Well, both methods are actually “legit” and will work nicely. But some flaming troll master code ninjas will probably kick up a huge fuss and insist that we must do it the object-oriented way… As it looks more “advanced” and professional.

    I will not argue with that and recommend it as well. The object-oriented way to create elements is just a lot cleaner, without having to write all those manual HTML tags. Still, there is nothing wrong to writing HTML strings and inserting them into the container… HTML is plain text to begin with.

    EXTRA
    DOWNLOAD & SUMMARY

    That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.

    SUMMARY – DOM FUNCTIONS YOU SHOULD KNOW

    and rows 
    document.getElementById(ID)Get element for the given ID.
    document.createElement(TAG)Creates a new DOM element.
    ELEMENT.appendChild(OBJECT)Append the given object into the specified element.
    TABLE.insertRow()Add a new row to the table.
    ROW.insertCell()Add a new cell to the table row.

    EXAMPLE CODE DOWNLOAD

    Click here to download all the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
      

    CLOSING
    WHAT’S NEXT?

    Thank you for reading, and we have come to the end of this short guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    The post How to Create Table From Array In Javascript appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Create Table From Array In Javascript

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×