1

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 )
cronoklee
  • 6,482
  • 9
  • 52
  • 80
  • Could you show the code you've written? – lonesomeday May 25 '11 at 20:09
  • 2
    I would load it in a temp table, then switch it over after it's rendered.... – Brad Christie May 25 '11 at 20:12
  • Thanks @Brad - great idea to fix the scrolling problem but I'm running uploads in some cells which are being cancelled when the innerHTML changes – cronoklee May 25 '11 at 20:18
  • the point of a temp table is to avoid changing the innerHTML. You'll now be working with DOM objects that you can manipulate, move, etc. innerHTML will re-trigger the rendering module. using appendChild, etc. will only effect what it needs to. – Brad Christie May 25 '11 at 20:24
  • Took some finesse, but this should work: http://jsfiddle.net/bradchristie/qLxrC/1/ – Brad Christie May 25 '11 at 21:02

8 Answers8

6

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.

bobince
  • 528,062
  • 107
  • 651
  • 834
2
function parseHTML(html) {
    var el = document.createElement("div");
    el.innerHTML = html;

    return el.childNodes;
}

var nodes = parseHTML("<span>Text</span>");
cem
  • 1,911
  • 12
  • 16
  • This is the best answer IMO, though it will return a NodeList so you would want to return `el.childNodes[0];` – Guy Dec 16 '20 at 19:46
1

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.

Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • OP: "I'm not using jQuery for this project so I'd like to do it without it if possible." – Swivel Jul 30 '13 at 16:55
  • 1
    @Swivelgames: You missed huge, all-uppercase "_UPDATE_" and some text before that part of the question. My answer was added 3 minutes before OP updated the question (proof: http://stackoverflow.com/posts/6130237/revisions). Cheers. – Tadeck Jul 30 '13 at 20:45
1

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.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

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?

Community
  • 1
  • 1
Nick
  • 19,198
  • 51
  • 185
  • 312
0

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.

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Thanks, yeah I thought of that myself but theres a lot of tds with various classnames and ids so its pretty messy to do it this way. – cronoklee May 25 '11 at 20:18
  • 1
    You don't have to only access the nodes through the `id`s though. You could walk the DOM and mantain references to the ``s manually (with an array or something like that), in a way that would be convenient for your logic later.. – hugomg May 25 '11 at 20:25
  • Plus you can always define a helper function to avoid having to create text nodes and set attribute values so explicitly. End up with something like `myTable.tBodies[0].appendChild(make('tr', {className: 'thing'}, make('td', {colSpan= 2}, 'Hello '+name)))`... – bobince May 25 '11 at 20:46
0

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
}
cronoklee
  • 6,482
  • 9
  • 52
  • 80
-1

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

Alvin
  • 10,308
  • 8
  • 37
  • 49
  • Actually, he doesn't need jquery, the cloneNode(true) method is part of the dom api and cross-browser compatible (see http://www.quirksmode.org/dom/w3c_core.html ) – Stefaan Colman May 25 '11 at 20:13
  • 2
    -1; JQuery (without context) isn't the magic solution to everything. – hugomg May 25 '11 at 20:19
  • To be fair, @cronoklee initially requested "a function or class", which definitely includes jQuery or any other library for that matter. – Jeremy May 25 '11 at 20:24
  • Agreed, my original intention was to suggest a library that cronoklee can use to simplify his problem. I probably should have put in as comment rather than an answer. – Alvin May 25 '11 at 20:38