2
 var $table = $('<table/>').addClass('commentbox');

$table.append('<tr><td>' + 'Comment Id:'+ '</td></tr>');

var $wrap = $('<div/>').attr('id', 'container');

var $in = $('<input type="button" value="Reply"/>').attr('id', 'reply');
$wrap.append($in);
 $table.append(
                 $('<tr>')
                         .append($('<td>'),
                         $('<td>'))
                       );
      $table.append($wrap);

I want the div id container to be added inside td but I am getting html

 <table>
   <tbody>
    <tr>
      <td>Comment</td>
     </tr>
     <tr>
        <td>
        </td><td></td>
     </tr>
  <tbody>
     <div id="container">
      <input type="button" value="Reply" id="reply">
     </div>
</table>
coder25
  • 2,363
  • 12
  • 57
  • 104

3 Answers3

5

You need to append the $wrap object to the <td> element, not the $table.

Try something like this instead:

var $table = $('<table/>').addClass('commentbox');

$table.append('<tr><td>' + 'Comment Id:'+ '</td></tr>');

var $wrap = $('<div/>').attr('id', 'container');
var $in   = $('<input type="button" value="Reply"/>').attr('id', 'reply');

$wrap.append($in);

$table.append(
    $('<tr>').append($('<td>').append($wrap), $('<td>').html('hello'))
);

Demo here: http://jsfiddle.net/umCDP/

Ayman Safadi
  • 11,502
  • 1
  • 27
  • 41
0

You could also use directly Javascript to create the HTML:

var table = document.createElement("table");

var tbody = document.createElement("tbody");
var tr_comment = document.createElement("tr");
var td_comment = document.createElement("td");
td_comment.appendChild(document.createTextNode("Comment"));
tr_comment.appendChild(td);
tbody.appendChild(tr_comment);

var tr_container = document.createElement("tr");
var td_container = document.createElement("td");
var div_container = document.createElement("div");
div_container.setAttribute("id", "container");
var input = document.createElement("input");
input.setAttribute("type", "button");
input.setAttribute("value", "Reply");
input.setAttribute("id", "reply");
div_container.appendChild(input);
td_container.appendChild(div_container);
tr_container.appendChild(td_container);
tbody.appendChild(tr_container);

table.appendChild(tbody);

Adding elements using Javascript, should improve performance.

What is the most efficient way to create HTML elements using jQuery?

Community
  • 1
  • 1
Stelian Matei
  • 11,553
  • 2
  • 25
  • 29
0

You need to append to the $('table tbody'). Example:

$('table tbody').append($('<tr><td>new row</td></tr>'));
Thach Mai
  • 915
  • 1
  • 6
  • 16