admin管理员组

文章数量:1391955

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

function test_function(){
    code = '<img src=".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.

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

function test_function(){
    code = '<img src="http://www.myimage./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.

Share Improve this question edited Aug 21, 2018 at 18:22 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Nov 22, 2010 at 10:28 DavidDavid 16.8k35 gold badges110 silver badges169 bronze badges 9
  • 1 what doctype do you use? – Dror Commented Nov 22, 2010 at 10:31
  • With which browsers are you experiencing this? – JAL Commented Nov 22, 2010 at 10:31
  • If the browser removes the forward slash, it is likely to be not required in that doctype. – Pekka Commented Nov 22, 2010 at 10:32
  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "w3/TR/xhtml1/DTD/xhtml1-transitional.dtd"> – David Commented Nov 22, 2010 at 10:33
  • But do you serve your web page as application/xhtml+xml? – Marcel Korpel Commented Nov 22, 2010 at 10:39
 |  Show 4 more ments

1 Answer 1

Reset to default 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.

本文标签: javascriptinnerHTML removing closing slash from image tagStack Overflow