mardi 27 octobre 2015

Adding elements to the DOM tree, Help creating a table in Javascript

I am a beginner working on an assignment for a class. The assignment is asking us to create a blank html file with html, meta, title, and body tags. It then instructs us to populate this html file using a javascript code with the following details:

A 4x4 table with a header row counting as one of the 4 rows.
4 buttons labeled up/down/left/right. A fifth button labeled 'Mark Cell'. ... I will spare you the rest of the details. It is this first part I am having trouble with as I have already created the other portions.

I wrote the following code to address the first portion.

var table = document.createElement('table');
var header = document.createThead();
var frstRow = document.createElement('tr');
var databits = document.createElement('td');
frstRow.appendChild(databits);
header.appendChild(frstRow);
table.appendChild(header);
----------------------Everything Below this line works by itself...but it is missing a header

    for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   


    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');
    table.style.border="1px solid black";
    td1.style.border="1px solid black";
    td2.style.border="1px solid black";
    td3.style.border="1px solid black";
    td4.style.border="1px solid black";

    var text1 = document.createTextNode(i);
    var text2 = document.createTextNode(i);
    var text3 = document.createTextNode(i);
    var text4 = document.createTextNode(i);

    td1.appendChild(text1);
    td2.appendChild(text2);
    td3.appendChild(text3);
    td4.appendChild(text4);
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);


    table.appendChild(tr);
}

document.body.appendChild(table);

If I do everything underneath the line I drew, it works. It shows up as a 3rx4c table. I want to add a Th to the top of this table so I thought that I could add the code to the top for a table header and the corresponding row and td for that header. I am apparently wrong as when I do this, nothing displays!

What am I doing wrong?




Aucun commentaire:

Enregistrer un commentaire