Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript document.write is not working

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...

like image 263
Maria Ines Parnisari Avatar asked Aug 13 '26 16:08

Maria Ines Parnisari


2 Answers

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>');
like image 173
DarkAjax Avatar answered Aug 16 '26 06:08

DarkAjax


You're not escaping the quotes in your strings. It should be:

document.write("<a href=\"index.html\">Home</a>");

Otherwise, JavaScript thinks the string ends after href= and the rest of the line does not follow valid JavaScript syntax.

As @Felix mentioned, the JavaScript debugger tools will be extremely helpful in letting you know what's going on.

like image 30
Jrop Avatar answered Aug 16 '26 08:08

Jrop