0

I am using the following code in javascript's document.write method :

    <script type="text/javascript">
      document.write("<font color="blue">["+time()+"]</font>");
    </script>

But this doesn't seem to work. Please guide me.

semantic_c0d3r
  • 789
  • 2
  • 14
  • 31
  • The right syntax for `document.write` is not to use it. http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – KooiInc May 08 '12 at 06:37

3 Answers3

4

The problem has nothing to do with HTML directly, simply with how string literals work in JavaScript (and pretty much every other programming language). If you want to use a " character inside a JavaScript string that is delimited with " characters then you must escape it: \". Alternatively use ' to delimit either the string or the attribute values.

document.write("<font color=\"blue\">["+time()+"]</font>");
document.write('<font color="blue">['+time()+"]</font>");
document.write("<font color='blue'>["+time()+"]</font>");

That said, generating HTML using document.write usually isn't a great idea (it only works at load time, is usually better replaced with more reliable server side code or more reusable DOM manipulation)) and the font element is deprecated.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1
<script type="text/javascript">
      document.write("<font color=\"blue\">[" + time() + "]</font>");
</script>

or

<script type="text/javascript">
      document.write('<font color="blue">[' + time() + ']</font>');
</script>

Note that time doesn't exist as a function in JavaScript—I'm assuming you made a function above that wasn't included in your code snippet. Also you shouldn't really use document.write for anything unless you're just experimenting. You could test all this out using console.log in Firefox's Firebug or Safari / Chrome Web Inspector, would be way faster for experimenting than full page refreshes. Also noticed how I added spaces on either side of the + sign: way easier to read.

Mauvis Ledford
  • 35,240
  • 13
  • 77
  • 84
-1
var color = 'blue';     
document.write("<font color="+color+">["+time()+"]</font>");

Or

 document.write("<font color='blue'>["+time()+"]</font>");
Oyeme
  • 10,385
  • 4
  • 33
  • 59