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 without resetting existing content? 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:

element.innerHTML = newHTML + element.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 )

Answers:

Answer

Are you attempting to insert content into an existing element, without disturbing the content that's already in there?

The most straightforward answer is insertAdjacentHTML. This is an IE scripting extension, since standardised by HTML5:

mydiv.insertAdjacentHTML('afterBegin', '<p>Some new stuff</p><p>to prepend</p>');

Unfortunately it is not implemented everywhere. So elsewhere you have to create a new element, set innerHTML on it and then transfer the contents to the target:

var container= document.createElement('div');
container.innerHTML= '<p>Some new stuff</p><p>to prepend</p>';
while (container.lastChild)
    mydiv.insertBefore(container.lastChild, mydiv.firstChild);

If you have a lot of new content, this will be slow. You can speed it up on browsers that support DOM Range by making a Range over the new content, extracting it to a DocumentFragment and inserting that fragment into the target node in one go.

Unfortunately (again), whether you are using insertAdjacentHTML or innerHTML, there are elements that IE<9 won't set HTML on: most notably <table> and its relations. So in that case you have to surround the HTML in a suitable wrapper for the element name:

container.innerHTML= '<table><tbody>'+newRowsHTML+'</tbody></table>';

and then extract the contents from the inner element to put in the target.

The good thing about this is that with tables if you have a lot of new rows you can put them in a single <tbody> and insertBefore/appendChild that body to put all the rows in in one go, which is quicker than one-by-one.

Answer
function parseHTML(html) {
    var el = document.createElement("div");
    el.innerHTML = html;

    return el.childNodes;
}

var nodes = parseHTML("<span>Text</span>");
Answer

DISCLAIMER: I don't write code these days out of jQuery. SImply because I hate chasing down the browser quirks between using property A on this browser, and property B on this one. That said, this works in Firefox, but is more about getting the concept down. I just wanted to be as up-front as possible.

DEMO

Basically, you do the following:

  1. Have your <table> that contains all the "original" / "untainted" data you don't want fussed with. [table1]
  2. Have a string with additional data you need inserted in to this original table, without manipulating (or otherwise impeding) on whatever is already going on with table1. [sampleData]
  3. Create a new <table> [table2] and add it to the document (but style it so it's completely invisible). Depending on the content of the string, you may use a <div>, but whichever method you go it should be invisible (after all, all we're using it for is the ability to parse the html string using innerHTML).
  4. Now take the contents of that new <table> [table2] (or <div>) and use javascript and DOM to push those items tot he new table.

This will avoid using innerHTML again on the new table, forcing a reload and losing anything that's going on already.

Answer

Use for example jQuery (documentation of the specific method - with examples - is here):

var your_html_code = '<table>...</table>';

then use it like that:

jQuery(your_html_code);

See more within similar question page.

Answer

I think I understand what you are trying to do. If you need a .NET library that will let you easly parse HTMl try Html Agility Pack

You could parse html just like you parse xml using the XMLDocument api in .NET. This is a .NET dll so you would have to do this on the server side of coarse. If you need the DOM to be manipulated without post back you could always create a service on the web server and make an ajax call that includes the html.

Does that make sense?

Answer

innerHTML is the way to go. Perhaps you could try reseting the inner HTML of only the <td>s you are changing and see if that gives the effect you want?

You could also have a look at the table manipulation methods in the DOM.

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
}
Answer

Have you look into JQuery (if you're allowed to use it)?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.