How to use innerHTML property In Javascript

The innerHTML property allows us to set or get the HTML content within an element. This method is concise and straightforward for creating tables.

Syntax:

selectedElement.innerHTML = "value";

Example: The below code implements the innerHTML property to create an HTML table using a JavaScript array.

HTML




<!DOCTYPE html>
<html lang="en">
 
<body>
    <script>
        const data = [
            { name: 'Rahul', age: 25, city: 'New Delhi' },
            { name: 'Vijay', age: 30, city: 'Muzaffarpur' },
            { name: 'Gaurav', age: 22, city: 'Noida' },
        ];
 
        function createTableWithInnerHTML() {
            let tableHTML = '<table border="1"><tr>';
 
            Object.keys(data[0]).forEach(key => {
                tableHTML += `<th>${key}</th>`;
            });
 
            tableHTML += '</tr>';
 
            data.forEach(item => {
                tableHTML += '<tr>';
                Object.values(item).forEach(value => {
                    tableHTML += `<td>${value}</td>`;
                });
                tableHTML += '</tr>';
            });
 
            tableHTML += '</table>';
 
            document.body.innerHTML += tableHTML;
        }
 
        createTableWithInnerHTML();
    </script>
</body>
 
</html>


Output:

How to Create an HTML Table from an Object Array Using JavaScript ?

Tables are a fundamental part of web development, and displaying data in a structured manner is a common requirement. JavaScript provides a powerful way to dynamically generate HTML content, making it easy to create tables from object arrays.

Table of Content

  • Using innerHTML property
  • Using appendChild() method

Similar Reads

Using innerHTML property

The innerHTML property allows us to set or get the HTML content within an element. This method is concise and straightforward for creating tables....

Using appendChild() method

...