5

This is very odd. Here is a quick test function:

function test_function(){
    code = '<img src="http://www.myimage.com/img.jpg" alt="image" />';
    alert(code);
    document.getElementById('test').innerHTML = code;
    alert(document.getElementById('test').innerHTML);
}

Running the code above will show /> in the first alert, but the second alert doesn't, it shows just >. So it looks like applying to .innerHTML strips out the forward slash. Any ideas how to stop this from happening? I need the forward slash for validation.

9
  • 1
    what doctype do you use?
    – Dror
    Nov 22, 2010 at 10:31
  • With which browsers are you experiencing this?
    – JAL
    Nov 22, 2010 at 10:31
  • If the browser removes the forward slash, it is likely to be not required in that doctype.
    – Pekka
    Nov 22, 2010 at 10:32
  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    – David
    Nov 22, 2010 at 10:33
  • But do you serve your web page as application/xhtml+xml? Nov 22, 2010 at 10:39

1 Answer 1

7

The second alert just shows you what the browser uses as its internal representation of your image element. You don't need the slash for validation, as validation always is about your page's source, validators don't execute JavaScript that dynamically adds elements to the DOM.

In fact, most browsers handle XHTML internally just the same as HTML, not as an XML-representation of your document. Only when you send your XHTML document with MIME-type application/xhtml+xml, some browsers will render your page using the XML parser.

Also see Ian Hickson's article.

4
  • Thats all well and good, unless you are using things like innerHTML to save page source into an ajax page editor.
    – David
    Nov 22, 2010 at 10:37
  • Right, so if I use that mime, it will work in some browser. I need something sure fire and can't find anything online apart form using that mime.
    – David
    Nov 22, 2010 at 11:01
  • @David – Can't you switch to HTML 5 here? It is much more forgiving when you don't use self-closing tags. Nov 22, 2010 at 11:15
  • To work around this, parse the string and add it manually: stackoverflow.com/q/8764669/2065702 Feb 25, 2020 at 14:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.