<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="content">My First Paragraph</p>
<script type="text/javascript">
document.getElementById("content").innerHTML="Edited using JavaScript";
</script>
</body>
</html>
The HTML <script> tag is used to insert a JavaScript into an HTML document. Inside the <script> tag use the type attribute to define the scripting language (e.g type="text/javascript"). The <script> and </script> tells where the JavaScript starts and ends. The lines between the <script> and </script> contain the JavaScript and are executed by the browser:
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. Add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, as follows
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("content").innerHTML="Edited using JavaScript";
//-->
</script>
</body>
</html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.
The following example writes a <p> element into the HTML document:
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<script type="text/javascript">
document.write("<p>Added using JavaScript</p>");
</script>
</body>
</html>
The problem here is that, the entire HTML page will be overwritten if document.write() is used inside a function. So we must use document.getElementById() to avoid overwritten entire HTML page.
No comments:
Post a Comment