Home > Web Front-end > JS Tutorial > How to Create Complex HTML Tables with Rowspans and Merged Cells Using JavaScript?

How to Create Complex HTML Tables with Rowspans and Merged Cells Using JavaScript?

Barbara Streisand
Release: 2024-10-19 08:17:01
Original
343 people have browsed it

How to Create Complex HTML Tables with Rowspans and Merged Cells Using JavaScript?

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 &amp;&amp; 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 &amp;&amp; j === 1) {
          td.setAttribute('rowSpan', '2');
        }
      }
    }
  }
  body.appendChild(tbl);
}

tableCreate();</code>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template