innerHTML property may be non-standard, but it can be a lot more
convienient than fiddling around with the DOM
methods to insert a chunk of XHTML
into a page. Currently Mozilla doesn’t allow the use of
innerHTML to insert markup
into documents served as application/xhtml+xml, so here is a class that attempts to provide similar
innerHTML for these documents.
The class essentially takes a string of well-formed XHTML
and parses it into a DOM tree. These nodes are then
inserted into the document. This means we can be sure the document remains well-formed after we’ve modified it, whereas if we were using
innerHTML we wouldn’t be able to guarantee this.
The only method of the class that you need to use is the
write method. It accepts up to
idfor an element in the page. If this value is omitted it defaults to the
bodyof the page.
write returns true if the content could be inserted and false if there was an error, that is
if the markup being inserted was not well-formed.
If we want to write a couple of paragraphs of text into an element with the
id container —
appending this new content to the end of any existing content in the element. We first include the DomInnerHtml.js file into the page, then use,
var dih = new DomInnerHtml(); dih.write('<p>Hello world</p><p>This is a test</p>', false, 'container');
To insert the content. If the browser does not support
DOMParser which is used to convert the string into a DOM tree then
innerHTML is used to insert the content instead. As far as i’m aware all the browsers that don’t support
DOMParser either don’t support application/xhtml+xml in the first place (eg IE) or allow
innerHTML to be used to insert content into the page anyway (eg Opera).
I guess it should be possible to simplify this script massively using
document.importNode as in Tarquin’s example on UserJS.org however I have had problems getting this to work as I would like. Essentially the content is inserted but it has no styling — not even the browser’s default stylesheet. So
p tags are displayed inline,
strong is displayed with normal font weight and so on… In Mozilla it seems you can re-apply the missing styles (though it would be tedious to do so), but I can’t make this work at all in Opera.
It should also be noted the Tarquin is far more likely to be right than I am ;-)
The problems with elements having no styles as noted above is because the nodes created need to have the XHTML namespace. I’ve written a new script that takes this into account. Use this new function instead of the class presented here.
There are currently no comments for this item.
Sorry, comments for this item are currently closed.