Question

I need to create two tables. Both tables are created in JScript, Because they need to be created dynamically. I know when you make two html tables, you can separate them by assigning a tag as follows:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

But in my jScript, I created the first table as follows:

function makeCells() {
    var t = document.createElement("TABLE");

    for (var rows = 0; rows < 8; rows++) {
        var newRow = document.createElement("TR");
        console.log(newRow);
        t.appendChild(newRow);
        for (var cols = 0; cols < 8; cols++) {
            var newCell = document.createElement("TD");
            newRow.appendChild(newCell);
        }
    }
    document.body.appendChild(t);
}

So how would I go about creating two tables with different names/tags so I can then use them with two different CSS statements?

Was it helpful?

Solution

How about...

function createTable(className) {
  var t = document.createElement("TABLE");
  t.className = className || "";

  for (var rows = 0; rows < 8; rows++) {
    var newRow = document.createElement("TR");
    console.log(newRow);
    t.appendChild(newRow);
    for (var cols = 0; cols < 8; cols++) {
        var newCell = document.createElement("TD");
        newRow.appendChild(newCell);
    }
  }
  document.body.appendChild(t); 
}

createTable("table1");
createTable("table2");

As a side note, if you're not aware, most modern browsers feature some sort of Dev Tools - hit F12 in Chrome, IE or Firefox, and it should pop up. Within each there is a 'Console' section, (Esc in Chrome) and you can not only execute javascript but browse the available functions and properties. To answer your question, I opened up Chrome's dev tools and did:

var t = document.createElement("TABLE");
t.     // <-- browsed the list of available properties of t, found className and classList
t.className = "table1";
t      // Output: <table class="table1"></table>

I added this in the hopes that you will come away with the knowledge of how to see what is available to you and not just memorization of ".className" :-P

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top