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?

1
  • 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. Commented Jun 27, 2010 at 15:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I ran the W3C xhtml markup validation on it indeed gives no errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.