views:

30

answers:

1

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?

+4  A: 

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
I ran the W3C xhtml markup validation on it indeed gives no errors.
Roel V.