JavaScript document.write is not working

Maria Ines Parnisari picture Maria Ines Parnisari · Aug 16, 2013 · Viewed 11.2k times · Source

Sorry if this seems dumb, i'm new to JavaScript.

This is in menu.js:

document.write("<a href="index.html">Home</a>");
document.write("<a href="news.html">News</a>");
document.write("<a href="about.html">About us</a>");

This is in index.html:

<head>
</head>
<body>
    <script type="text/javascript" src="menu.js"></script>
</body>
</html>

When I load index.html, nothing comes up...

Answer

DarkAjax picture DarkAjax · Aug 16, 2013

The problem is your quotes, you're using " both to delimit your new elements and to set their href attribute, change your code to:

document.write("<a href='index.html'>Home</a>");
document.write("<a href='news.html'>News</a>");
document.write("<a href='about.html'>About us</a>");

Or:

document.write('<a href="index.html">Home</a>');
document.write('<a href="news.html">News</a>');
document.write('<a href="about.html">About us</a>');

Combining single (') and double (") quotes. You could also escape your internal quotes (document.write("<a href=\"index.html\">Home</a>");

BUT it'd be better to use a single call to document.write(), like this:

document.write('<a href="index.html">Home</a>' 
    + '<a href="news.html">News</a>'
    + '<a href="about.html">About us</a>');