Open links in new tab
  1. Copilot Answer
    123

    Creating a table in JavaScript involves using the document.createElement method to dynamically generate table elements and append them to the DOM.

    Example

    function createTable() {
    // Get reference to the body
    var body = document.getElementsByTagName("body")[0];

    // Create table and tbody elements
    var tbl = document.createElement("table");
    var tblBody = document.createElement("tbody");

    // Create rows and cells
    for (var i = 0; i < 3; i++) {
    var row = document.createElement("tr");
    for (var j = 0; j < 2; j++) {
    var cell = document.createElement("td");
    var cellText = document.createTextNode(`Cell ${i},${j}`);
    cell.appendChild(cellText);
    row.appendChild(cell);
    }
    tblBody.appendChild(row);
    }

    // Append tbody to table and table to body
    tbl.appendChild(tblBody);
    body.appendChild(tbl);

    // Set table border attribute
    tbl.setAttribute("border", "2");
    }

    createTable();

    Explanation

    1. Creating Elements: Use document.createElement to create table, tbody, tr, and td elements.

    2. Appending Elements: Append child elements (td) to their parent (tr), then append rows (tr) to the table body (tbody), and finally append the table body to the table.

    3. Setting Attributes: Use setAttribute to set attributes like border.

    Considerations

    • Styling: Use CSS for styling instead of setting attributes directly in JavaScript.

    • Dynamic Data: You can modify the function to accept parameters for rows, columns, and data.

    Continue reading
Refresh