Home >Web Front-end >JS Tutorial >How to Modify a Table Creation Function to Achieve a Specific Layout with Varying Row and Cell Counts in JavaScript?
Given a JavaScript function designed to create a table with 3 rows and 2 cells, this question seeks guidance on how to modify it to replicate a given table layout where there are 3 rows, but only 2 cells in the first and third rows, while the second row has only one cell that spans two rows.
Adapting the JavaScript Code:
The existing function can be adapted using a more succinct approach with the insertRow and insertCell methods, as shown below:
<code class="js">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); }</code>
This code:
Final Result:
Executing the modified tableCreate function will generate a table with the given layout:
Cell I0/J0 | Cell I0/J1 |
Cell I1/J0 | Cell I1/J1 |
Cell I2/J0 |
The above is the detailed content of How to Modify a Table Creation Function to Achieve a Specific Layout with Varying Row and Cell Counts in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!