Writing to The HTML Document
The example below writes a <p> element with current date information to the HTML document:Example
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body>
</html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body>
</html>
Try it yourself »
Changing HTML Elements
The example below writes the current date into an existing <p> element:Example
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>
Try it yourself »
Examples Explained
To insert a JavaScript into an HTML page, use the <script> tag.Inside the <script> tag use the type attribute to define the scripting language.
The <script> and </script> tells where the JavaScript starts and ends:
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>
<script type="text/javascript">
... some JavaScript code ...
</script>
</body>
</html>
<body>
<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>
<script type="text/javascript">
... some JavaScript code ...
</script>
</body>
</html>
In this case the browser will replace the content of the HTML element with id="demo", with the current date:
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>
<body>
<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>
Some Browsers do Not Support JavaScript
Browsers that do not support JavaScript, will display JavaScript as page content.To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript.
Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this:
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>
Comments
Post a Comment