I have a situation when there’s a table and you can add a new row by clicking a button. The row is dynamically generated by a server and it is passed back in HTML. So basically what i need to do is prefix the new row to the old table. Something like this:
tableelement.innerHTML = newHtml + tableelement.innerHTML;
That surely works, but i have a table header and, obviously, i need to insert the new html after it. How would i do this? insertBefore or insertAfter can’t help (afaik), because they’re meant for inserting elements and not unparsed HTML. So how could i, having an object of the header’s row, insert another row (in HTML) after it (or before) ?
Thank you for your ideas
I would consider rethinking the approach.
innerHTMLis read-only for tables in Internet Explorer, so you’re bound to run into interoperability issues with your current method. You could restructure your code to build the elements using the DOM instead of specifying theinnerHTML. It’s fairly straightforward, much more efficient (doesn’t invoke the parser) and more cross-browser compatible.Mozilla seems to agree with Microsoft on this, and to quote the
element.innerHTMLdocumentation:The process involves using the DOM Level 2 methods,
table.insertRow()andtr.insertCell(). For a decent read, see Building Tables Dynamically (MSDN).Example (from MDC):