3. Create a function that generates the table HTML markup based on the data array. For example:
4. Call the generateTable function with the data array and append the resulting HTML markup to the table container element. For example:
5. Optionally, you can style the table using CSS to make it look more visually appealing. For example:
That's it! You now have a dynamic table that can be updated with new data as needed.
Here's another example that generates a dynamic table using user input.
This code generates an input form where the user can specify the number of rows and columns they want in the table. When the user clicks the "Generate Table" button, the generateTable() function is called. This function retrieves the user input values, generates an HTML table with the specified number of rows and columns, and inserts the table into the table-container element.
Note that:- This example does not use an array of data like the previous example, but instead generates the table content dynamically using loops. You can modify the loop logic to generate different table content as needed.
Here's another example that generates a dynamic table using data from an external API.
This code uses the fetch() method to retrieve data from an external API (https://jsonplaceholder.typicode.com/users). The API returns an array of user objects, which are used to generate an HTML table with three columns (Name, Email, and Phone). The async/await syntax is used to handle the asynchronous nature of the fetch() method.
Note that:- In this example, the generateTable() function is called automatically when the page loads, so the table is generated without the need for user input. You can modify the API endpoint to retrieve different data, and the table columns and content will update accordingly.