roopurt18 Posted January 28, 2007 Share Posted January 28, 2007 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 objectfunction htmlDom_html2dom(html){ var obj = null; if(html.length > 0){ obj = document.createElement('div'); obj.innerHTML = html; } return obj.firstChild;}[/code] Quote Link to comment Share on other sites More sharing options...
roopurt18 Posted January 28, 2007 Author Share Posted January 28, 2007 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 objectfunction 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.