Search code examples
javascripthtmlhtml-tableyui

Is there a way to add raw html as new table rows with javascript?


Let's say I have the following table:

<table>
  <tr id="1">...</tr>
  <tr id="2">..</tr>
  ...
  <tr id="last">..</tr>
</table>

I also have a third-party service from which I get some raw html, also table rows like this:

<tr id="additional-1">...</tr>
<tr id="additional2">...</tr>

Is there a relatively simple javascript way to insert those new rows after the tr with the id "last"?

I'm asking for simple built-in ways to avoid having to do a lot of parsing, replacing and stuff.

I prefer YUI 3 to jQuery solution.


Solution

  • Wrap the string in <table><tbody>..rows here...</tbody></table>. Then, create a dummy element, eg <div>, and set the innerHTML property to the previously constructed string. Finally, loop through all rows, and move the rows to the table using insertBefore(newelem, reference).
    This method also works in IE, where setting the innerHTML property on a cell triggers an error.

    var raw_html, prev_element, last_element_parent, rows, i;
    raw_html = '<tr>....etc....</tr>';
    prev_element = document.getElementById('last_element');
    last_element_parent = prev_element.parentNode;
    
    dummy = document.createElement('div');
    dummy.innerHTML = '<table><tbody>' + raw_html + '</tbody></table>';
    rows = dummy.firstChild.rows;
    
    for (i=rows.length-1; i>=0; i--) {
        last_element_parent.insertBefore(rows[i], prev_element.nextSibling);
    }