Debt Consolidation - Debt Consolidation - Find jobs - Wordpress Themes - Bad Credit Loans

PDA

View Full Version : Dynamic insert a table with style...


fungyup
Mar 12th 2008, 3:49 am
Hi all,

I have created a <table> node by document.createElement('table'), insertRow() and insertCell(). A simple <table id="myTable"><tr><td></td></tr></table> structure is created and append to the html.

My target is to assign a CSS style to this dynamic table. I tried using document.getElementById("myTable").style.className = "myCssStyle", I found that the script doesn't take effect to the table... but .style.backgroundColor = "#123456" works....

Why does Js behave like this....? I took a wrong approach?

Thanks...

vpguy
Mar 12th 2008, 5:58 pm
There is no style named className. className is an attribute.

Correct: obj.className = "cssclass";

Incorrect: obj.style.className = "cssclass";

fungyup
Mar 12th 2008, 7:09 pm
I tried both... still cannot..

I get the table node by Id and "alert" the innerHTML. I saw the class attribute is set but the screen doesn't take effect...

rkquest
Mar 13th 2008, 5:20 am
There are two ways you can do this. Refer to the script below for the first one:


<html>

<head>
<script type="text/javascript">
function createTable() {
element = document.createElement('table');
element.className = "myClass"; // 1st method
tr = element.insertRow(-1);
td = tr.insertCell(-1);
td.innerHTML = 'test';
document.getElementById('container').appendChild(element);
}
</script>
<style type="text/css">
.myClass {
background-color: #CCCCCC;
}
</style>
</head>

<body>
<a href="javascript:createTable()">Create Table</a>
<div id="container"></div>
</body>

</html>


The second method is when you replace the commented line...


element.className = "myClass";


.. with this one..


element.setAttribute("class", "myClass");


You can run the script to see if it works.

Hope that helps.

fungyup
Mar 13th 2008, 11:04 pm
OH I found the different is....
The table class must be assigned before append to the html...

Thanks for your great help!!