3

How do I prepend/append columns at beginning/end of my html table after exited with </table>markup?

(when before hitting the </table> mark)

  • <tr> naturally appends rows
  • <td> naturally appends cols/cells to the row

Javasript has a way of catching the table afterwards and modify the table: E.g. table.insertRow() with some functionality on where to insert the row. Also, a kind of table.prepend() function exists, but which I cant really get working.

My table is horizontally scrollable, so I want to load more data (more columns) when user scrolls all the way to the end, both left and right. I have a way of detecting this but it's the action afterwards I'm having difficulties with.

Isn't there a table.insertColumn(hereOrThere)somewhere... hidden? ;)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
niCk cAMel
  • 869
  • 1
  • 10
  • 26
  • this will solve it for you : https://stackoverflow.com/questions/2007357/how-to-set-dom-element-as-the-first-child. You just have to create your new row and then do .insertBefore the firstchild. Details on that link ... – trk Aug 25 '17 at 20:36
  • 1
    `insertBefore` is a good idea but a better one could be a `` element specific method to insert a cell at a specific index that you prefer. Enter... [`HTMLTableRowElement.insertCell()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell) where you can specifiy the index of the cell as an argument like `rows.forEach(tr => tr.inserCell(0).appendChild(document.createTextNode('New cell'));` – Redu Aug 25 '17 at 21:33
  • @Redu that is indeed a cool way to do it. – trk Aug 26 '17 at 01:12
  • Tnx guys. I'm don't really see a practical way for me to implement @(82Tuskers) suggestions. But just quickly tried out @Redu 's suggestion with .insertCell() and it works!!! I'm gonna implement it and see how it handles reality ;) – niCk cAMel Aug 27 '17 at 19:03
  • Though I followed the example in @Redu 's link and not his javascript hack in the comment! (What is `rows`? the row element? then what is `tr`? – niCk cAMel Aug 27 '17 at 19:09
  • `rows` is just a nodeList of `` tagged nodes within a ``. Such as when you do like `rows = document.querySelectorAll("#myTable tr")` where `"myTable"` is the `id` of the subject table like `< table id ="myTable">`
    – Redu Aug 27 '17 at 19:32
  • @Redu Aah good. Got it! – niCk cAMel Aug 27 '17 at 20:42
  • @Redu but man, put ur comment in an answer. Easier for others to find.. – niCk cAMel Aug 27 '17 at 20:42

1 Answers1

4

there is no built in way to prepend a column but you can do it by looping over all the rows, and preprending a cell to each row

function prependColumn(column) {
  $('tr').each((i, tr) => {
    $(tr).prepend('<td>' + column[i] + '</td>')
  })
}

prependColumn(['cell0','cell1', 'cell2', 'cell3'])
gafi
  • 12,113
  • 2
  • 30
  • 32