user3767481
user3767481

Reputation: 327

How to incorporate CSS into a table

I would like to put CSS code into my table but don't want to styles at every row of the table. I have the following code:

CSS:

.statetable th
{
    width: 250px;
    color: red;
    text-align: left;
}
.statetable tr
{
    width: 250px;
}

JavaScript:

function showState()
{       
    myTable = "<table class='statetable'><br><th><td>Type</td>";
    myTable += "<td>Value</td></th>";

    createRow("------------------", "------------");
    createRow("Layout", (document.getElementById("startradio").form.format == "Default"));
    myTable +="</table>";
    document.getElementById("tableHolder").innerHTML = myTable;
}

function createRow(type, value)
{
    myTable += "<table class='statetable'><tr><td>" + type + "</td>";
    myTable += "<td>" + value + "</td></tr>";
}

HTML:

 <input type="button" id="button" value="Click to show states" onclick="showState()"/>
 <div id="tableHolder"></div>

The style is not working though. I have placed my th and tr's and placed the css with them but I am not sure what am I doing wrong.

Upvotes: 0

Views: 72

Answers (2)

user3950597
user3950597

Reputation:

You are ending up with more starting <table> tags then closing ones. The createRow() method should not return a starting <table> tag.

Also, .set width on the table instead of the <tr>/<th>.

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72839

Replace these:

myTable = "<table class='statetable'><br><th><td>Type</td>";
myTable += "<td>Value</td></th>";

With these:

myTable = "<table class='statetable'><tr><th>Type</th>";
myTable += "<th>Value</th></tr>";

Also, in createRow, replace:

myTable += "<table class='statetable'><tr><td>" + type + "</td>";
myTable += "<td>" + value + "</td></tr>";

With:

myTable += "<tr><td>" + type + "</td><td>" + value + "</td></tr>";

Upvotes: 1

Related Questions