Open In App

Understanding basic JavaScript code

Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. <script> tags can be put between the <head> and </head> tags or between <body> and </body> tags. type attribute was the most important attribute of <script> tag. However, it is no longer used. The browser understands that <script> tag has JavaScript code inside it.

Syntax:



<script type="text/javascript">
  ...
</script>

How to write, save and run codes:

Method 1:



Method 2: 

Example: Code for Painting the page light blue.




<!DOCTYPE html>
<html>
  
<head>
    <title></title>
</head>
  
<body bgcolor="white">
    <p>Paragraph 1</p>
    <script type="text/javascript">
        document.bgColor ="lightblue";
    </script>
</body>
<html>

Output: The colour of the web page is light blue, but the opening body tag is defined to set the background colour to be white.

 

Above code explanation:

Example: Code to write something to a web page using JavaScript, let’s write “Hello World!” to a blank page using JavaScript.




<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
                      http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
  
<head>
    <title></title>
</head>
  
<body>
    <p id="ResultsP"></p>
    <script type="text/javascript">
             // Script Block 1
              document.getElementById('ResultsP').innerHTML ='Hello World!';
    </script>
</body>
<html>

Output:

Above code explanation:

Things you should remember:

  1. A page is known as a document for the purpose of scripting in a web page. 
  2. Properties of the document can be referenced by writing a document followed by a dot, followed by the property name. The document has lots of properties. 
  3. After the <script> tag browser starts to interpret the text as JavaScript until the </script> comes.  

Article Tags :