0

I'm trying to create a table from an ajax json response but my for loop sets i to the max value instantly.

$.ajax(settings).done(function (response) {
  console.log(response);
  var i = "";
  td = document.createElement('td');
  tr = document.createElement('tr');
  tableContent = document.getElementById('analysisTable');
  for (i = 0; i < response.segments.length; ++i) {
    td.innerHTML = response.segments[i].confidence;
    $(td).attr({
      'id': i,
      'class': "analysis",
    });
    tableContent.appendChild(tr).appendChild(td);
  }
});
George
  • 6,630
  • 2
  • 29
  • 36
isetnt
  • 11
  • 1
  • 3
  • You're probably overwriting your previous appends every time. – Shilly Nov 09 '18 at 14:15
  • 2
    You are creating a single `` and a single ``. You will at the very least need to create a `` for each segment element. –  Nov 09 '18 at 14:17
  • Here's the proper jQuery way to do this: https://jsfiddle.net/khrismuc/ycn9qspw/ –  Nov 09 '18 at 14:23
  • "my for loop sets i to the max value instantly." if you use the debugger to step through your code it will be trivial to see that this is not what is happening at all. The symptoms of your problem might make it look like that, but as others have said, it's because you keep overwriting the same variable every time, so all references to that variable which you add to the DOM will contain the same content (and since it's a loop, it'll be whatever the content was the last time the loop ran). – ADyson Nov 09 '18 at 14:29

1 Answers1

-1

You're creating the tr and td elements outside the loop. Re-Setting the innerHtml does not create new elements.