Jump to content

Solution: Convert string of HTML to DOM node / object.


roopurt18

Recommended Posts

I have an AJAX application that receives strings of HTML from the server to plug into the document.  I know there's a big debate between creating DOM objects the "correct" way vs. using innerHTML.  I myself prefer to use the "correct" way when possible, but when the server is returning a long string of HTML it's much more convenient to use innerHTML.

However, part of my current application is a form and FF has the odd habit of resetting the form when you append to the innerHTML of the form.  Rather than write a long sequence of code to save the values and restore them afterwards, I came up with a quick and easy way to convert a string of HTML into a proper DOM object that I could append to the form, thus preventing FF from resetting the user's information.

Enjoy:
[code]
// htmlDom_html2dom
// html - the html string
// Convert a string of html text to a dom object
function htmlDom_html2dom(html){
  var obj = null;
  if(html.length > 0){
    obj = document.createElement('div');
    obj.innerHTML = html;
  }
  return obj.firstChild;
}
[/code]
Link to comment
Share on other sites

Quick update.  The function should probably be changed to:

[code]
// htmlDom_html2dom
// html - the html string
// Convert a string of html text to a dom object
function htmlDom_html2dom(html){
  if(html.length > 0){
    var obj = document.createElement('div');
    if(obj){
      obj.innerHTML = html;
      return obj.firstChild;
    }
  }
  return null;
}
[/code]

Also, keep in mind that it only returns the first child.  I had originally wrote this for an HTML string that started with a [i]table[/i] tag.

If you tried it with the following HTML string:
[code]
<div>
  1
</div>
<div>
  2
</div>
[/code]

You would only get the first div back from the function.  Just keep that in mind when using it or tailor it to suit your needs better.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.