cronoklee cronoklee - 6 months ago 31
Javascript Question

Javascript function to parse HTML string into DOM?

Is there a good JS function or class that can seamlessly parse a string of HTML into the DOM? I'm trying to find an easy way to duplicate a complicated table row at the top of the table.

It obviously will work like this:

table.innerHTML = newHTML + table.innerHTML;


However, this causes the browser to reload the entire table which resets the scroll position and deletes any unsaved editable content in the table.

UPDATE:

I'm not using jQuery for this project. Here's an idea I found somewhere but I cant get it working:

var templateRow = document.getElementById( 'templateRow' );
var newhtml = "<tr id='row"+lastID+"'>"+'templateRow'.innerHTML+"</tr>";
var range = document.createRange();
range.selectNode( 'templateRow' );
var parsedHTML = range.createContextualFragment( newhtml );
templateRow.appendChild( parsedHTML )

Answer

Sincere thanks for all the replies - some of which are quite detailed. I've managed to solve the problem using a combination of table.insertRow() and innerHTML. It seems to be the quickest and most clean solution to the problem. Hope it and the other replies on this page help someone else out!

Rather than updating the entire table html, we add a new row to the DOM and insert the html into that:

function $(id){ //just a shortcut function
    return document.getElementById(id);
}

var lastID = 10;  //id number of last table row

function addRow(){
    var newhtml = $('templateRow').innerHTML); //copy the template row
    var t = $('aTable').insertRow(2) //insert a row in the desired position
    t.id = 'row'+lastID; //update the new tr's id
    t.innerHTML = newhtml //replace the innerHTML of the new row
    lastID++; //increment the counter for next time
}