tags:

views:

102

answers:

2

I'll post the two solutions I have tried, and what failed with each one:

First:

var table = document.createElement("table");
table.addClass("nice");
// fails because table does not have the "addClass" method

Second:

var table = $(document.createElement("table"));
table.addClass("nice");
var row = table.insertRow(-1);
// fails because table does not have the "insertRow" method (it has been cleared by jQuery)

How can I properly create a table and add rows and cells to it using jQuery?

+4  A: 
var table = $('<table>')
  .addClass('nice');

To add rows, just create elements and append them to the table.

Pointy
Shouldn't be `$('<table />')` ?
Alex Bagnolini
@Alex - It doesn't matter, it's flexible.
meder
Thanks, I'm new to jQuery and didn't know I could do it like that. But does IE6 support this? I remember trying something like this (without jQuery, using document.createElement("tr")) and IE6 crashing or something like that. Anyway, antique browser, no one cares anymore. Thanks!
Felix
+1  A: 
var table = $('<table>').addClass('foo').append( $('<tr>').append( $('<td>').text('lol') ) ).appendTo('body')

It helps storing them in multiple variables, obviously.

meder