0

As I recall, the following iteration schemes produce a matrix. In my case a 5x5

  SCRIPT Language="JavaScript">
  document.write('<table border="1" cellspacing="1" cellpadding="5">')
  for(i = 0; i < 5; i++){
  document.write('<tr>')
    for (j = 0; j < 5; j++){
       document.write('<td>row ' + i + ', column ' + j + '</td>')
    }
    document.write('</tr>')
 }

 document.write('</table>')

 //-->
 </SCRIPT>

How would I wrap this in a div class that is set up with a margin and background color?

user2948897
  • 169
  • 3
  • 9
  • Do you want the `div` as part of the script? Are you wanting to instert the contents into an exisig `div`? What have you tried to date and what went wrong? – Jon P Feb 21 '14 at 02:53
  • DigitalFront has it figured out. Thanks for the comment. – user2948897 Feb 21 '14 at 02:55

3 Answers3

1

Something like this:

<SCRIPT Language="JavaScript">
  document.write('<div style="margin: 10px; background-color: blue;"><table border="1" cellspacing="1" cellpadding="5">')
  for(i = 0; i < 5; i++){
  document.write('<tr>')
    for (j = 0; j < 5; j++){
       document.write('<td>row ' + i + ', column ' + j + '</td>')
    }
    document.write('</tr>')
 }

 document.write('</table></div>')

 //-->
 </SCRIPT>
Tyler Day
  • 1,690
  • 12
  • 12
0

if you have to use document.write, and just want to wrap your table in a div, this would do it.

document.write('<div class="myclass" style="margin:5px; background-color:#000;">');
document.write('<table border="1" cellspacing="1" cellpadding="5">');
for(i = 0; i < 5; i++){
    document.write('<tr>');
    for (j = 0; j < 5; j++){
       document.write('<td>row ' + i + ', column ' + j + '</td>');
    }
    document.write('</tr>');
}
document.write('</table>');
document.write('</div>');

this wraps it and puts style to it, but I could have misunderstood your question.

Gisheri
  • 1,645
  • 2
  • 18
  • 27
0

I wouldn't do it that way, I'd go something like:

<div id="divWithTable" class="someClassName"></div>

<SCRIPT Language="JavaScript">
   var ourDiv = document.getElementById("divWithTable");
   var tableHTML = "<table>" 

   for(i = 0; i < 5; i++){
     tableHTML += "<tr>";

     for (j = 0; j < 5; j++){
        tableHTML += "<td>row " + i + ", column " + j + "</td>"
     }

     tableHTML += "</tr>";  
    }

  tableHTML +="</table>";

  ourDiv.innerHTML = tableHTML;

//-->
</SCRIPT>

For your CSS use

.someClassName
{
    background-color:#F00;
    margin: 0.5em;
}

 // cellpadding
.someClassName table th, .someClassName table td { padding: 5px; }

// cellspacing
.someClassName table { border-collapse: separate; border-spacing: 5px; } 

This way you keep style seperate and only update the DOM once

As you have labled your question HTML5 note that many table attributes are no longer part of the HTML5 spec and shouldn't be used. See this answer for more info.

See it in action here: http://jsfiddle.net/tbH8y/.

Community
  • 1
  • 1
Jon P
  • 19,442
  • 8
  • 49
  • 72