Home > Web Front-end > JS Tutorial > How to Create a Custom Table Structure with Javascript?

How to Create a Custom Table Structure with Javascript?

Mary-Kate Olsen
Release: 2024-10-19 08:13:30
Original
1038 people have browsed it

How to Create a Custom Table Structure with Javascript?

Creating a Specific Table Structure Using JavaScript

Your request involves creating a table with a unique structure, differing from the one you have provided in your code. To achieve this, let's explore a modified version of your JavaScript function:

<code class="javascript">function createTable() {
  // Get the body element for table insertion
  var body = document.querySelector("body");

  // Create the table and table body elements
  var table = document.createElement("table");
  table.style.width = "100%";
  table.style.border = "1px solid black";
  var tableBody = document.createElement("tbody");

  // Set up the table rows and columns
  for (var i = 0; i < 3; i++) {
    var row = tableBody.insertRow();
    for (var j = 0; j < 2; j++) {
      if (i === 2 && j === 1) {
        // Skip cell for the bottom right corner
        continue;
      } else {
        var cell = row.insertCell();
        cell.appendChild(document.createTextNode(`Cell at row ${i}, column ${j}`));
        cell.style.border = "1px solid black";
        if (i === 1 && j === 1) {
          // Set a rowspan of 2 for the specific cell
          cell.setAttribute("rowspan", "2");
        }
      }
    }
  }

  // Append the table body to the table
  table.appendChild(tableBody);

  // Append the table to the body of the page
  body.appendChild(table);
}

createTable();</code>
Copy after login

In this modified code, we utilize the insertRow() and insertCell() methods to create the table rows and cells directly. The key differences and optimizations include:

  • Using CSS styling to set the table width and border instead of the border attribute on the table element.
  • Creating a rowspan of 2 for the cell in the second row and second column.
  • Skipping cell creation for the bottom right corner where no cell is needed.
  • Using a consistent naming convention for variables (camelCase) for clarity.

The above is the detailed content of How to Create a Custom Table Structure with 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