PDA

View Full Version : Literal XHTML tags are improperly formed when generated via document.createElement()


apv
10-18-2006, 10:00 PM
I'm scripting a little utility much like Alex King's wonderful little js_quicktags. I thought it would make more sense (and be more compact, easier to manipulate, etc) to use the DOM directly to create the tags instead of cobbling together plain text HTML.

It works but the literal tags brought back are not XHTML (even when the parent document is XHTML strict; I suppose it only matters for standalone tags like img and br). I've only tested in FireFox and Safari so far.

Here is a minimal script to show the problem:


var container = document.createElement('div');
var tag = document.createElement('br');
container.appendChild(tag);
alert(container.innerHTML);


The alert text should be "<br/>" or "<br />." But in FireFox it is "<br>" and in Safari it is "<BR />."

I've searched around but can't find ways to manipulate/control the DOM or whatever would be necessary to get the right output.

Ideas? Or is it just not really feasible to do compactly (meaning Alex's approach is best)?

Thank you!

jkd
10-18-2006, 11:35 PM
Is your document actually XHTML (e.g. served as application/xhtml+xml or any other XML mime-type)? An XHTML doctype doesn't put any browser into XHTML mode.

Assuming that it is indeed using an XML DOM, note the property name, innerHTML. You would expect it to return valid HTML, not necessarily XHTML. If you want to get at the actual DOM serialization, do this:

var str = (new XMLSerializer()).serializeToString(theElementNode);

That should work in Opera 9 and Firefox, and gets the correct, XML serialization of the node.

apv
10-19-2006, 12:03 AM
Nice. So, both ideas do work differently than the original and together they work correctly.

Just changing to this:


var str = (new XMLSerializer()).serializeToString(tag);
alert(str);


Gets to "<BR/>" in FireFox (doesn't work in Safari but I don't care for now).

And, either with the serialize or with just innerHTML again, serving it with the right server header, "application/xhtml+xml," does it perfectly, "<br/>."

Thank you very much for the quick and astute reply.