Stranger Stranger - 6 months ago 14
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

$td.html(obj.itemName);
$tr.append($td);
$td.html(obj.itemCount);
$tr.append($td);
$td.html(obj.itemPrice);
$tr.append($td);
$("#profile").find("table tbody").append($tr);
$tr.empty();
$td.empty();
})


By the above code I expect each iteration will give me the following result:
<tr><td>obj.itemName</td><td>obj.itemCount</td><td>obj.itemPrice</td></tr>
. 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

I use no library, so this may work:

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

selectedItems.forEach(function(obj){
  var aRow = [
    obj.itemName,
    obj.itemCount,
    obj.itemPrice
  ]; // 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 = [
    obj.itemName,
    obj.itemCount,
    obj.itemPrice
  ];
  var $tr = $('<tr></tr>');
  $.each(aElements, function(i,str) { // append all elements into $tr
    var $td = $('<td></td>').html(str);
    $tr.append($td);
  });

  $tmp.append($tr);
});

$("#profile").find("table tbody").append($tmp.html()); // append content only once
Comments