Using HTML and JavaScript to Create a Table

Posted by





Create a Table Using HTML and JavaScript


Create a Table Using HTML and JavaScript

Tables are a great way to display data in a structured and organized manner. In this article, we will show you how to create a simple table using HTML and then populate it with data using JavaScript.

Step 1: Creating a Table in HTML

To create a table in HTML, you can use the <table> tag. Inside the <table> tag, you can use the <tr> tag to create a new row, and the <td> tag to create a cell within each row. You can use the <th> tag to create header cells.

        <table>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Location</th>
            </tr>
            <tr>
                <td>John</td>
                <td>25</td>
                <td>New York</td>
            </tr>
            <tr>
                <td>Jane</td>
                <td>30</td>
                <td>London</td>
            </tr>
        </table>
    

Step 2: Populating the Table Using JavaScript

Now that we have created a basic table structure in HTML, we can use JavaScript to populate it with data dynamically. First, let’s give our table an id so that we can reference it in our JavaScript code:

        <table id="myTable">
            ...
        </table>
    

Then, we can use JavaScript to access the table by its id, and then add new rows and cells to it using the insertRow() and insertCell() methods:

        let table = document.getElementById('myTable');

        let row = table.insertRow();
        let cell1 = row.insertCell(0);
        let cell2 = row.insertCell(1);
        let cell3 = row.insertCell(2);
        cell1.innerHTML = 'Jim';
        cell2.innerHTML = '28';
        cell3.innerHTML = 'Paris';
    

With this JavaScript code, we have added a new row to the table with the data for a person named Jim who is 28 years old and lives in Paris.

Conclusion

Tables are a useful tool for displaying data in a structured and organized format. By using HTML and JavaScript, you can easily create and populate tables with data to enhance the user experience on your website.


0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Yojo
7 months ago

The right is cut