views:

120

answers:

4

I 've got a very interesting thing with an html here.

<html>
<head>
<script language="Javascript">
 var str="me&myhtml";
 function delimit(){
  document.write(str);
  document.write("<hr>");

 }
</script>
</head>
<body onload="delimit()">
</body>
</html>

You see 'me&myhtml' with a line beneath. However, if you comment //document.write("<hr>"); then you just see 'me', which is weird.

Thing is, javascript normally doesn't read '&', but rather interprets as a command. However, if you have any document.write() with at least 6 characters, or a 'br', or 'hr', then it displays '&' as it is.

Any ideas?

+3  A: 

Try str = "me&amp;myhtml";

Scoregraphic
A: 

It probably has to do with the fact that & is essentially an escaping character in HTML. If you want to write out an ampersand to the page, you should use &amp;

Rudd Zwolinski
rishi
+9  A: 

If there is no HTML tag after &myhtml JavaScript or the HTML rendering engine probably interprets it as an unrecognized or incomplete entity (lacking an ending ;) and does not render it. If you follow me&myhtml with an HTML tag, then JavaScript or the HTML rendering engine recognizes that &myhtml is not an incomplete entity because it is followed by an HTML tag instead of a ;.

It doesn't matter what HTML tag you follow the string with, <a> or <p> work just as well as <br>.

The behavior is not consistent across all browsers. IE 6, 7 & 8 and Firefox 2, 3 & 3.5 behave the way you describe, Safari for Windows 3 & 4 render nothing when you comment out the second document.write() or do something like document.write("abc");. Opera 9.64 & 10b3 render the text correctly regardless of the content of the second write().

Note that using document.write() in the onload event without writing out correctly formatted and valid HTML (complete with doctype and <html>, <head>, etc) is probably a bug anyway. Note the problem does not manifest itself if you do:

<html>
<head>
<script>
function delimit() {
    document.write('me&myhtml');
}
</script>
</head>
<body>
<script>
delimit();
</script>
</body>
</html>

To answer your question, it is a bug in either the implementation of a specification, or an undefined part of a specification that each browser implements differently. What you are doing is slightly incorrect, the outcome of that slightly incorrect code is not defined and it can not be relied on to behave consistently across all of the major browsers in use today. What you are doing should be avoided.

Grant Wagner
Very nice answer
shambleh
idrumgood
Thanks for the nice clarification.
rishi
+1  A: 
bobince
Alohci