How to use appendChild() method In Javascript
The appendChild() method can be used to dynamically append the created HTML to a selected DOM element by passing the HTML as parameter to it. It appends HTML as child of the selected element.
Syntax:
selectedElement.appendChild('HTMLToAppend');
Example: The below code implements the appendChild() method to dynamically create a HTML table from JavaScript object.
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 createTableWithForEach() { const table = document.createElement('table'); table.setAttribute('border', '1'); const headerRow = document.createElement('tr'); Object.keys(data[0]).forEach(key => { const th = document.createElement('th'); th.appendChild(document.createTextNode(key)); headerRow.appendChild(th); }); table.appendChild(headerRow); data.forEach(item => { const row = document.createElement('tr'); Object.values(item).forEach(value => { const td = document.createElement('td'); td.appendChild(document.createTextNode(value)); row.appendChild(td); }); table.appendChild(row); }); document.body.appendChild(table); } createTableWithForEach(); </ 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