Search code examples
javascriptdocument.write

What is the right syntax to use in document.write for tags with attributes?


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. How can I fix it?


Solution

  • The problem has nothing to do with HTML directly, but 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 and is usually better replaced with more reliable server-side code or more reusable DOM manipulation)) and the font element is deprecated.