How To Display Objects From Array Into HTML Table
enter image description hereI am working on a Shopping Cart problem and I have a table in HTML to input various objects in an Array. I want to create a 'edit' button to display the
Solution 1:
the right way to create an element in javascript, would be something like that
<div class="some"></div>
function addElement () { 
  // create new "p" element
  var newP = document.createElement("p"); 
  // add content --  the data you want display
  var newContent = document.createTextNode("hello, how are you?"); 
  newP.appendChild(newContent); //add content inside the element. 
  // add the element and content to DOM 
  var currentDiv = document.getElementById("some"); 
  document.body.insertBefore(newP, currentDiv); 
}
addElement();
https://developer.mozilla.org/es/docs/Web/API/Document/createElement
Now, if we adapt that information to the context of the tables, we can do it on this way to generate the data dynamically
   arr = [
  'item 1',
  'item 2',
  'item 3',
  'item 4',
  'item 5'
         ];
function addElement () { 
arr.forEach(function(el,index,array){
  let tableRef = document.getElementById('some');
  // Insert a row at the end of the table
  let newRow = tableRef.insertRow(-1);
  // Insert a cell in the row at index 0
  let newCell = newRow.insertCell(0);
  // Append a text node to the cell
  let newText = document.createTextNode(el);
  newCell.appendChild(newText);
});
}
addElement();
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell
link to demo: Fiddle
Post a Comment for "How To Display Objects From Array Into HTML Table"