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...
There is no style named className. className is an attribute. Correct: obj.className = "cssclass"; Incorrect: obj.style.className = "cssclass";
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...
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> HTML: The second method is when you replace the commented line... element.className = "myClass"; Code (markup): .. with this one.. element.setAttribute("class", "myClass"); Code (markup): You can run the script to see if it works. Hope that helps.
OH I found the different is.... The table class must be assigned before append to the html... Thanks for your great help!!