3

Possible Duplicate:
How to create xhtml elements with javascript
Creating a <br /> with javascript createElement?

I'm working with the programmatic generation of forms with JavaScript, e.g.:

document.createElement();
document.appendChild;
inputExample.type = "text";
…

but I realized that the JavaScript generation of self-closing [X]HTML/XML elements isn't applicable, i.e.

document.createElement('input');

will result in <input>, not <input />.

While the page has a

<!DOCTYPE html>

and

<html xmlns="http://www.w3.org/1999/xhtml">…</html>

and is part of a browser extension thus being interpreted with a MIME type of text/html, therefore not needing to syntactically conform to XHTML, I would like to know of a way for JavaScript element creation to generate valid XHTML. Is there a way to do this?

Community
  • 1
  • 1
terrygarcia
  • 477
  • 5
  • 22
  • 3
    Possible duplicate: [http://stackoverflow.com/questions/4654265/creating-a-br-with-javascript-createelement](http://stackoverflow.com/questions/4654265/creating-a-br-with-javascript-createelement) – Will Oct 05 '11 at 01:40
  • 1
    Out of curiosity, would you mind saying why you need to generate the XHTML? Normally you would only be concerned about generating whatever-style html for client use or well formed "just XML" XML for the server. – hugomg Oct 05 '11 at 03:00
  • This is not a duplicate of that question, it is the opposite. The OP here wants to generate markup from the element. The linked possible duplicate is the opposite. – RobG Oct 05 '11 at 03:10

1 Answers1

5

When you call createElement, you are creating a DOM object, there is no markup involved. The only mechanisms for generating markup are the innerHTML and outerHTML properties that have been standardised to some extent in HTML5.

Those properties should generate markup using the HTML fragment serialization algorithm in an HTML document or the XML fragment serialization algorithm in an XML document. Perhaps the properties should have been called innerMarkup and outerMarkup.

I don't think there is any way to call one serialiser or the other specifically using script (e.g. to call the XML serializer from within an HTML document), though you may be able to parse trivial markup from the HTML serialiser and turn it into something approximating XHTML.

By the way, as far as I know there is no such thing as "XHTML5". The current standard for HTML is version 4.01. HTML5 is a working draft that may never be standardised. There are also XHTML 1.0 and XHTML 1.1 that are used as DOCTYPEs in documents that are nearly always served as text/HTML (to serve them as anything else would not be sensible) and so are treated as HTML documents.

RobG
  • 142,382
  • 31
  • 172
  • 209