0

How can I dynamicaly create xhtml elements with javascript? I want to add a checkbox inside a table cell.

So I want the code to look like this:

<td>
    <input type="checkbox" />
</td>

Unfortunatly the slash at the end of the input element is not added thus making it not xhtml compatible. The result of my code looks like this:

<td>
    <input type="checkbox">
</td>

I tried both innerHTML as createElement but both didn't add the slash.

1)

cell.innerHTML = "<input type='checkbox' />";

2)

var checkbox = document.createElement("input");
checkbox.type = "checkbox";
cell.appendChild(checkbox);

Is there a way to add an xhtml emement?

Roel V.
  • 55
  • 1
  • 4
  • 1
    What do you mean *not compatible*? Do you mean invalid? This is code you are injecting with JavaScript and therefore separate from your XHTML markup. You wrote valid XHTML, but you are at the mercy of the JavaScript parser. So unless this is breaking something, I wouldn't worry about it. – Jason McCreary Jun 27 '10 at 15:26

1 Answers1

4

XHTML is just another input language into the common DOM. What sets XHTML syntax apart is how it is *parsed**, not how it is represented in the DOM. So your code is fine - you ARE adding the element successfully, it's just translated when it hits the DOM.

* except Internet Explorer, which, despite declaring XHTML as the doctype, IE will parse it as HTML anyway.

Matt
  • 43,482
  • 6
  • 101
  • 102