Hey all,
Sorry if this is a newbie question, but does javascript have a built-in
function that will take a string, parse any HTML tags from the string
If you mean ECMAScript, no. However Microsoft introduced innerHTML some
time ago (with IE 4) and it has been widely copied. You can create DOM
elements from an HTML string by setting an existing element's innerHTML to
the string.
and return back a DOM element representing the root of the HTML tree
represented by the string?
No, not even innerHTML will do that. It is a property of an element, so
you have to set the innerHTML of some existing element or create a new
element and set its innerHTML property.
The W3C DOM includes documentFragment, but for the browsers I tested
(Firefox) you can't set it's innerHTML property.
For example is I called
HTML2DOM('<strong>foo</strong>''), it would return the 'strong' element
with one text element child with the value of 'foo'.
Use:
var strongEl = document.createElement('strong');
strongEl.appendChild(document.createTextNode('foo'));
You could probably create your own function that creates a div element,
sets its innerHTML property, replaces the div with a document fragment
(i.e. attach all the child nodes of the div to the fragment in the correct
order) then returns a reference to the fragment.
Something like (untested):
function toDOM(HTMLstring)
{
var d = document.createElement('div');
d.innerHTML = HTMLstring;
var docFrag = document.createDocumentFragment();
for (var i=0, len=d.childNodes.length; i<len; ++i){
docFrag.appendChild(d.childNodes
);
}
return docFrag;
}
innerHTML is not supported consistently in all browsers and feature
detection is difficult. Errors in the HTML string or invalid markup will
cause unpredictable results in different browsers.