-1

I am attempting to prepend a <tr><th>{...}</th><td>{...}</td></tr> to the following html element:

<table>
   <tbody>
        // Prepend element here...
        <tr>
            <th>Something here</th>
            <td>{...}</td>
        </tr>
        <tr>
            <th>Another thing here</th>
            <td>{...}</td>
        </tr>
    </tbody>
</table>

How could I prepend the element outlined above to <tbody> utilising vanilla js?

j08691
  • 204,283
  • 31
  • 260
  • 272
Maff
  • 1,032
  • 4
  • 25
  • 42

2 Answers2

2
var parentNode = document.querySelector('tbody'),
newChild = document.createElement('button'),
refChild = parentNode.firstElementChild;
parentNode.insertBefore(newChild, refChild);
adriaan
  • 1,088
  • 1
  • 12
  • 29
Todd
  • 5,314
  • 3
  • 28
  • 45
-1

If you give tbody an ID ('tbodyElement' in my example) you can try something like this...

var tbody = document.getElementById('tbodyElement');
tbody.innerHTML = '<tr><th>{...}</th><td>{...}</td></tr>' + tbody.innerHTML;
Jack Traynor
  • 139
  • 2