Vin Breau
Vin Breau

Reputation: 279

Why is this Javascript printing my comments in the rendered HTML

I'm new to Javascript, as in just really getting started with it today. I'm testing some very basic code in the first chapter of a book and encountered a problem on the first example. I wrote the code in Notepad++, but even in that program my second line of commenting is black and not green. Why does the line right after </noscript> render?

Code as rendered in Notepad++

The output to my browser is rendered as: Hello World! // Display a message dialog after the page has loaded.

<!DOCTYPE html>
<html>
<body>
    <div id = "panel">
    <script type = "text/javascript">
    // Dynamically write a text string as the page loads.
    document.write("Hello World!");
    </script>
    <noscript>Javascript is Not Enabled!</noscript>
    // Display a message dialog after the page has loaded.
    <body onload = " window.alert('Document Loaded!');">
    </div>
</body>
</html>

Upvotes: 1

Views: 2438

Answers (4)

Wellington Zanelli
Wellington Zanelli

Reputation: 1964

Your comment are not between script tag. You can move it into an script tag or use the HTML comment just like @22kar said. Also you need to put the parameter "onload" in the first body tag and remove the other one.

Upvotes: 1

Derek Henderson
Derek Henderson

Reputation: 9706

The reason the line you tried to comment out is rendered is because you have attempted to comment out the text with JavaScript comments.

The browser rendering html sees the two slashes (//) as part of the text, not as markup designating a comment.

The correct way to comment out something in html is with <!-- and -->.

Upvotes: 1

priteshbaviskar
priteshbaviskar

Reputation: 2327

<!-- This is a comment in HTML --> /* This is a comment in Javascript */

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

That's because you're writing your comment not in a JavaScript part but in an HTML one.

Comments in HTML are like this :

<noscript>Javascript is Not Enabled!</noscript> 
<!-- Display a message dialog after the page has loaded. -->

Note that you've put a body element inside the body, that's not good. You probably wanted this instead of the second body :

<script>
     window.onload = function(){
          alert('document loaded!');
     };
</script>

Upvotes: 8

Related Questions