ICoded
ICoded

Reputation: 341

innerHTML how to create new table row at the top

I got the table below which is generated by data. Further the button adds another row in the table. My question is, how can I modify the code, that the newly created row will appear on top of the table instead at the bottom.

Usually this can be done with .insertRow(0) but I want to use .innerHTML. Any ideas?

data = [{
    "property": "animal",
    "value": "dog"
  },
  {
    "property": "car",
    "value": "porsche"
  },
  {
    "property": "snacks",
    "value": "chips"
  }
]

var myTable = document.getElementById("myTable")

for (var i = 0; i < data.length; i++) {
  var row = `<tr>
      <td>${data[i].property}</td>
      <td>${data[i].value}</td>
    </tr>`

  myTable.innerHTML += row
}

var insertRow = document.getElementById("insertRow")

insertRow.addEventListener("click", function() {
  var row = `<tr>
       <td>property</td>
       <td>value</td>
    </tr>`
  myTable.innerHTML += row
})
#myTable {
  border-collapse: collapse;
}

#myTable td {
  border: 1px solid black;
  padding: 8px;
}

#delRow {
  width: auto;
  height: 30px;
}
<table id="myTable">
  <tbody>
    <!-- filled by script -->
  </tbody>
</table>

<button id="insertRow">+ Row</button>

Upvotes: 0

Views: 956

Answers (1)

myf
myf

Reputation: 11303

Generally prepending some string to another is done in re-assignment value = prefix + value; so in your code changing myTable.innerHTML += row to myTable.tBodies[0].innerHTML = row + myTable.tBodies[0].innerHTML would do the trick (I've added tBodies[0] just to make it more precise and save HTML parser some error fixing).

But in your case if you really need to build HTML from string, insertAdjacentHTML should be more appropriate and performant:

myTable.tBodies[0].insertAdjacentHTML('afterbegin', row);

<button onclick="
  myTbody.insertAdjacentHTML(
    'afterbegin',
    `<tr>
      <td>AA</td>
      <td>BB</td>
    </tr>`
  );"
>+ First Row</button>
 
<table border="1">
  <tbody id="myTbody">
    <tr>
      <td>CC</td>
      <td>DD</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions