javascript – Create table with jQuery – append

javascript – Create table with jQuery – append

This line:

n

$(#here_table).append( <tr><td> + result +  i + </td></tr> );n

n

Appends to the div#here_table not the new table.

n

There are several approaches:

n

/* Note that the whole content variable is just a string */nvar content = <table>nfor(i=0; i<3; i++){n    content += <tr><td> + result  +  i + </td></tr>;n}ncontent += </table>nn$(#here_table).append(content);n

n

But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.

n

But how about this one, it does what you expect nearly great:

n

var table = $(<table>).addClass(foo);nfor(i=0; i<3; i++){n    var row = $(<tr>).addClass(bar).text(result  + i);n    table.append(row);n}nn$(#here_table).append(table);n

n

Hope this would help.

You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.

n

$(#here_table).append(  <table /> );nn for(i=0;i<3;i++){n    $(#here_table table).append( <tr><td> + result +  i + </td></tr> );n}n

n

The main problem was that you were appending the tr to the div here_table.

n

Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop

n

var doc = document;nnvar fragment = doc.createDocumentFragment();nnfor (i = 0; i < 3; i++) {n    var tr = doc.createElement(tr);nn    var td = doc.createElement(td);n    td.innerHTML = content;nn    tr.appendChild(td);nn    //does not trigger reflown    fragment.appendChild(tr);n}nnvar table = doc.createElement(table);nntable.appendChild(fragment);nndoc.getElementById(here_table).appendChild(table);n

javascript – Create table with jQuery – append

When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.

n

You need to make the table first, then append it.

n

var $table = $(<table/>);nfor(var i=0; i<3; i++){n    $table.append( <tr><td> + result +  i + </td></tr> );n}n$(#here_table).append($table);n

Leave a Reply

Your email address will not be published.