Lab JavaScript 2
Lab JavaScript 2
1. Using innerHTML
2. Using document.write()
3. Using window.alert()
4. Using console
innerHTML
We use this method when we want display something into an HTML element. To access the HTML
element, we can use the document.getElementById(id) method.
The id attribute will identify the HTML element. We use innerHTML to define the HTML content.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>innerHTML</h1>
<p>Try this!</p>
<p id="test"></p>
<script>
document.getElementById("test").innerHTML = 4 + 6;
</script>
</body>
</html>
document.write()
We use this method to write something in the HTML document. By using this method after the
HTML document is loaded, all existing HTML will be deleted.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Demo</h1>
<script>document.write(4+6)</script>
</body>
</html>
NJ
ITT588 2
window.alert()
We also can use an alert box to display data.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Demo</h1>
<script>window.alert(4+6)</script>
</body>
</html>
console.log()
We can use console.log() method for debugging purpose.
Example:
<!DOCTYPE html>
<html>
<script language= "JavaScript">
var a=88, b= 98;
while(a!=b){
if (a > b){
a -= b;
}
if (a < b){
b -= a;
}
console.log("a=" + a + ", b=" + b);
}
document.write ("GCD is " + a);
</script>
<body style="text-align:center">
</body>
</html>
Save the above script as HTML document and run with your browser. Then open the Developer Tools
and click on Console.
NJ
ITT588 3
JavaScript Operator
JavaScript operators are quite similar like the other programming language. It has Arithmetic
Operators, Assignment Operators, String Operators, Comparison Operators, Logical Operator, Type
Operators and Bitwise Operators.
Activity 1
Activity 2
Write a JavaScript that: Prompt for an integer, then display the sum of the integers from 0 through
the number entered. For example, if you enter 14, then display 105 which is the sum of 0 + 1 + 2 +
3 + 4 + 5 + 6 + 7 + 8 + 9 + 10+11+12+13+14
Activity 3
Write a JavaScript that: Read a number (using prompt) and display it using alert.
Activity 4
Activity 5
Write a javaScript that convert from decimal to binary and binary to decimal.
NJ