Stranger Stranger - 2 years ago 61
jQuery Question

How to append created elements into table

I have

<div id="profile">... <table>...<tbody></tbody></table> </div>
. In script I get an array of objects and iterating over that array I want to add each object's information into a table row.

var $tr=$("<tr></tr>");
var $td=$("<td></td>");
$.each(selectedItems, function(index, obj){ //selectedItems is array of objects

$("#profile").find("table tbody").append($tr);

By the above code I expect each iteration will give me the following result:
. But I get nothing when I view html with google developer tools.
The selectedItems array is not empty (I checked it) and its objects are not empty too.
What should I do to get desired result?

Answer Source

I use no library, so this may work:

var profile = document.querySelector('#profile table tbody');
var domCollection = document.createElement("div");

  var aRow = [
  ]; // JH: 01 change their order to fullfil your wish, or add whatever you like

  var domTR = document.createElement('tr');  // JH: 02 create a <tr> element
  domTR.innerHTML = "<td>" + aRow.join('</td><td>') + "</td>" ;  // add content

  domCollection.appendChild( domTR );  // JH: 03 add this row into domCollection.

// JH: 04 put all rows into profile
profile.innerHTML += domCollection.innerHTML; // prevent update DOM tree too many times

if you like jQuery:

var $tmp = $('<div></div>');
$.each(selectedItems, function(index, obj){
  var aElements = [
  var $tr = $('<tr></tr>');
  $.each(aElements, function(i,str) { // append all elements into $tr
    var $td = $('<td></td>').html(str);


$("#profile").find("table tbody").append($tmp.html()); // append content only once
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download