Recreate a Complex HTML Table Structure Using JavaScript
In this article, we'll address a specific issue encountered by developers: creating a complex HTML table structure using JavaScript. Let's delve into the problem and its solution.
Problem:
A JavaScript function exists that creates a simple table with 3 rows and 2 columns. The challenge is to modify the function to generate a more complex table structure with varying rowspans and merged cells, as illustrated in the provided HTML code.
Solution:
To achieve this, we'll utilize the built-in insertRow and insertCell methods provided by HTML DOM. Here's the revised JavaScript code:
<code class="javascript">function tableCreate() { const body = document.body, tbl = document.createElement('table'); tbl.style.width = '100px'; tbl.style.border = '1px solid black'; for (let i = 0; i < 3; i++) { const tr = tbl.insertRow(); for (let j = 0; j < 2; j++) { if (i === 2 && j === 1) { break; } else { const td = tr.insertCell(); td.appendChild(document.createTextNode(`Cell I${i}/J${j}`)); td.style.border = '1px solid black'; if (i === 1 && j === 1) { td.setAttribute('rowSpan', '2'); } } } } body.appendChild(tbl); } tableCreate();</code>
Explanation:
The code iterates over the table rows and columns, creating individual cells using insertCell and setting their properties accordingly. The condition if (i === 1 && j === 1) { td.setAttribute('rowSpan', '2'); } is crucial. It handles the rowspan for the merged cell in row 2.
By using the insertRow and insertCell methods, we have greater control over the table structure, allowing us to quickly and dynamically create complex tables with varying rowspans and merged cells.
The above is the detailed content of How to Create Complex HTML Tables with Rowspans and Merged Cells Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!