views:

134

answers:

2

I'm using some code to build up tables using JQuery, but in Firefox 3.5.3 on Mac OSX, the table cells all appear on separate lines by themselves, instead of in their respective rows. Chrome 5.0.342.7 beta on OSX correctly produces the table, as does Safari 4.0.5.

Here is a minimal reproduction case:

<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;

<script type="text/javascript">
$(document).ready(function()
{
    var b = $('body');
    b.append("<table>");
    for (var i = 0; i < 3; ++i)
    {
        b.append("<tr>");
        for (var j = 0; j < 3; ++j)
            b.append("<td>x</td>");
        b.append("</tr>");
    }
    b.append("</table>");
});
</script>
</body>
</html>

In Chrome and Safari, I get this correct output:

x x x
x x x
x x x

but Firefox produces:

x
x
x
x
x
x
x
x
x

Note that if I manually create that exact table without using Javascript (i.e. direct into the HTML) then the table appears correctly in Firefox. Also, if I change the JS to append then entire table in one call then it also works -- the only time it doesn't work is if you append it part-by-part as I have done before.

My question is: is this to be expected, or should I report this as a bug to Firefox? I'm pretty sure this is a Firefox bug, but I'm a bit of a newbie to JS and web development in general, so perhaps there's something I'm missing?

P.S. obviously there are easy ways to get around this -- that's not my concern. See above.

+1  A: 

I don't think it makes sense to append the <tr> elements to the body - they're supposed to be inside the table. When you append the <table> element, you're appending a complete table element. To then add random table rows after that really makes no sense.

Do this instead:

var b = $('body'), t = $('<table/>');
for (var i = 0; i < 3; ++i) {
  var tr = $('<tr/>');
  for (var j = 0; j < 3; ++j) tr.append($('<td/>').text("x"));
  t.append(tr);
}
b.append(t);

That way, you're appending the table cell elements to each row, appending each row to the table, and finally appending the table to the body.

Pointy
That's totally besides the point.
Peter Alexander
No, it is **not** "beside the point". Do you actually know how the "append()" function works? You're here asking for help, and I'm trying to give it to you. Don't be so rude.
Pointy
It does work, just not in Firefox.
Peter Alexander
+1  A: 

You are trying to do to much that jQuery will handle for you try doing this:

var table = $("<table>");
for (var i = 0; i < 3; ++i) {
    var tr = $("<tr>").appendTo(table);
    for (var j = 0; j < 3; ++j)
        $("<td>x</td>").appendTo(tr);
}
table.appendTo('body');

jQuery will handle creating a DOM fragment for you and create your elements for you.

PetersenDidIt
Right! The "append" function is *not* about adding fragments of HTML source code to something, as the OP seems to have erroneously concluded.
Pointy