Dynamic insert a table with style...

Discussion in 'JavaScript' started by fungyup, Mar 12, 2008.

  1. #1
    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...
     
    fungyup, Mar 12, 2008 IP
  2. vpguy

    vpguy Guest

    Messages:
    275
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    There is no style named className. className is an attribute.

    Correct: obj.className = "cssclass";

    Incorrect: obj.style.className = "cssclass";
     
    vpguy, Mar 12, 2008 IP
  3. fungyup

    fungyup Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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...
     
    fungyup, Mar 12, 2008 IP
  4. rkquest

    rkquest Well-Known Member

    Messages:
    828
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    140
    #4
    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.
     
    rkquest, Mar 13, 2008 IP
  5. fungyup

    fungyup Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    OH I found the different is....
    The table class must be assigned before append to the html...

    Thanks for your great help!!
     
    fungyup, Mar 13, 2008 IP