View Full Version : JavaScript string with HTML --> node objects function?

12-03-2004, 07:21 PM
Has anyone seen a function that takes a string, parses any HTML, and returns it as an object with all its nodes?

So, for example this…

stringParser("<p>Here is the <strong>string</strong> we want to <em>add</em> to the page.</p>")

…would return the elementNode 'p' with it's children the textNodes, elementNodes 'strong' and 'em' and their textNode children. The object could then be added to the document via appendChild.

I'm thinking of developing a help system in which all of the help text is contained as an array in a liked js file, and when help is requested, the HTML is added to the DOM dynamically. Of course, if I don't act on the HTML string, it is printed verbatim in the browser.

Thanks in advance,


12-03-2004, 09:17 PM
cloneNode(true) does that, so inserting the strings into a documentFragment might work...

12-03-2004, 09:38 PM
The best answer here is:
- innerHTML
- Mozilla specific createContextualFragment
- Iew specific XMLDOM or DOMDocument
- Moz/Op specific XMLSerializer
- Opera supported W3C DOM3LS methods

No generic solution exists, except for the first point in the list, and this only work for HTML (text/html) documents anyway.

12-03-2004, 10:07 PM
innerHTML was just what I was looking for, since I am only working with text/HTML. By creating my object and setting innerHTML to my HTML string, the object tree is "imported" as desired.

Thanks so much for your quick response.