Skip to content Skip to sidebar Skip to footer

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>


functionaddElement () { 
  // create new "p" elementvar newP = document.createElement("p"); 
  // add content --  the data you want displayvar 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'
         ];

functionaddElement () { 

arr.forEach(function(el,index,array){
  let tableRef = document.getElementById('some');

  // Insert a row at the end of the tablelet newRow = tableRef.insertRow(-1);

  // Insert a cell in the row at index 0let newCell = newRow.insertCell(0);

  // Append a text node to the celllet 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"