coder25
coder25

Reputation: 2393

append div to td in table dynamically

 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>

Upvotes: 2

Views: 41249

Answers (3)

Thach Mai
Thach Mai

Reputation: 945

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

$('table tbody').append($('<tr><td>new row</td></tr>'));

Upvotes: 0

Stelian Matei
Stelian Matei

Reputation: 11623

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?

Upvotes: 0

Ayman Safadi
Ayman Safadi

Reputation: 11552

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/

Upvotes: 5

Related Questions