JavaScript and DOM
Introduction to JavaScript
JavaScript is a lightweight programming language widely used to make webpages interactive and dynamic.
HTML provides the structure of a webpage, CSS controls its appearance, and JavaScript adds behaviour and interactivity.
JavaScript can be used to:
- Respond to button clicks
- Change webpage content
- Change CSS styles
- Validate forms
- Display messages
- Perform calculations
- Work with HTML elements
- Communicate with web servers
- Create interactive applications
JavaScript was introduced in 1995 for use in the Netscape Navigator browser.
Features of JavaScript
Important features of JavaScript include:
1. Client-Side Execution
JavaScript commonly runs inside the user’s web browser.
This allows webpages to respond immediately to user actions without requiring every operation to be performed on the server.
2. Dynamic Webpage Manipulation
JavaScript can dynamically:
- Add elements
- Remove elements
- Change text
- Change attributes
- Change CSS styles
3. Event Handling
JavaScript can respond to user actions called events.
Examples include:
- Mouse Click
- Mouse Movement
- Key Press
- Form Submission
- Page Load
4. Asynchronous Programming
JavaScript supports asynchronous operations using technologies such as:
- Callbacks
- Promises
asyncawait
These allow certain operations to continue without blocking the entire webpage.
5. Cross-Browser Support
JavaScript is supported by major modern web browsers.
Examples include:
- Google Chrome
- Mozilla Firefox
- Microsoft Edge
- Safari
- Opera
6. DOM Manipulation
JavaScript can interact with the Document Object Model (DOM).
Using the DOM, JavaScript can access and modify webpage elements.
7. Communication with Servers
JavaScript can communicate with web servers and update parts of a webpage without reloading the complete page.
AJAX is one traditional technique used for this purpose.
8. Reusable Programming
JavaScript supports:
- Functions
- Objects
- Modules
These features help organize and reuse code.
History of JavaScript
JavaScript was created by Brendan Eich in 1995 while working at Netscape.
The language was initially known as:
- Mocha
- LiveScript
- JavaScript
JavaScript and Java are different programming languages despite the similarity of their names.
JavaScript was standardized as ECMAScript.
Some important versions mentioned in the chapter include:
- ECMAScript 5 — 2009
- ECMAScript 6 / ES6 / ECMAScript 2015 — 2015
JavaScript in Web Browsers
JavaScript is supported by major browsers.
Different browsers use different JavaScript engines to execute JavaScript code.
Browser settings can also allow JavaScript to be enabled or disabled.
The exact menu path depends on the browser and browser version.
JavaScript in HTML Documents
JavaScript can be included in HTML in three common ways:
- Embedded / Internal JavaScript
- Inline JavaScript
- External JavaScript
1. Embedded JavaScript
Embedded JavaScript is written inside a <script> element.
The <script> element may be placed in the <head> or <body>.
Example
<!DOCTYPE html>
<html>
<head>
<title>Embedded JavaScript</title>
<script>
function showMessage() {
alert("Hello, World!");
}
</script>
</head>
<body>
<button onclick="showMessage()">
Click Me
</button>
</body>
</html>
2. Inline JavaScript
Inline JavaScript is written directly inside an HTML element using an event attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript</title>
</head>
<body>
<button onclick="alert('Hello, World!')">
Click Me
</button>
</body>
</html>
Inline JavaScript is useful for small examples but is harder to maintain in larger projects.
3. External JavaScript
External JavaScript is stored in a separate .js file.
The JavaScript file is connected to HTML using:
<script src="script.js"></script>
HTML File
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="showMessage()">
Click Me
</button>
</body>
</html>
script.js
function showMessage() {
alert("Hello, World!");
}
Advantages of External JavaScript
- Better organization
- Reusable across pages
- Easier maintenance
- Separates structure from behaviour
- Suitable for larger programs
JavaScript Variables and Data Types
JavaScript variables are used to store data.
A variable can be considered a named container that stores a value.
Example:
var age = 15;
var name = "Rahul";
JavaScript is dynamically typed, meaning the variable type is determined from the value assigned to it.
JavaScript Data Types
The chapter classifies data types into:
- Primitive Data Types
- Non-Primitive / Reference Data Types
Primitive Data Types
The common primitive types discussed in the chapter are:
- String
- Number
- Boolean
- Undefined
- Null
String
A string represents text or a sequence of characters.
Example:
var name = "Nepal";
Number
A number represents numeric values.
Example:
var age = 15;
Boolean
A Boolean has two possible values:
true
or:
false
Example:
var isStudent = true;
Undefined
A variable that has been declared but has not been assigned a value may have the value:
undefined
Example:
var result;
Null
null represents an intentionally empty or absent value.
Example:
var data = null;
Non-Primitive Data Types
The source discusses:
- Object
- Array
- Regular Expression
Object
An object stores related data using properties and values.
Example:
var student = {
name: "Ram",
age: 15
};
Array
An array stores a collection of values.
Example:
var subjects = [
"HTML",
"CSS",
"JavaScript"
];
Regular Expression
A regular expression is used for pattern matching in text.
Example:
var pattern = /html/i;
JavaScript Variables
Variables can be declared using:
var
Modern JavaScript also commonly uses:
let
const
Variable Declaration
var money;
var name;
Multiple variables can also be declared together:
var money, name;
Variable Initialization
A value can be assigned when the variable is declared.
var name = "Ali";
var money = 2000.50;
JavaScript Variable Scope
Scope refers to the region of a program where a variable can be accessed.
The chapter discusses:
- Global Variable
- Local Variable
Global Variable
A global variable is declared outside a function and can be accessed from different parts of the script, subject to JavaScript’s scope rules.
Example:
var message = "Global";
function showMessage() {
document.write(message);
}
Local Variable
A local variable is declared inside a function and is normally accessible only within that function.
Example:
function showMessage() {
var message = "Local";
document.write(message);
}
Global and Local Variable Example
<!DOCTYPE html>
<html>
<body>
<script>
var myVar = "Global";
function checkScope() {
var myVar = "Local";
document.write(myVar);
}
checkScope();
</script>
</body>
</html>
Output:
Local
Rules for JavaScript Variable Names
Important rules include:
- Do not use reserved JavaScript keywords as variable names.
- Variable names should not begin with a digit.
- Names may begin with a letter,
_, or$. - JavaScript variable names are case-sensitive.
Example:
var name;
var Name;
These are two different variables.
Valid Variable Names
var student;
var studentName;
var _total;
var $price;
Invalid Variable Names
123name
student-name
HTML DOM
DOM stands for:
Document Object Model
The DOM represents an HTML document as a structured collection of objects.
JavaScript can use the DOM to:
- Find HTML elements
- Change content
- Change styles
- Change attributes
- Add elements
- Remove elements
- Respond to events
DOM Tree Concept
A simple HTML document:
<html>
<body>
<h1>Hello</h1>
<p>Welcome</p>
</body>
</html>
can be represented conceptually as:
Document
│
html
│
body
┌─┴─┐
h1 p
Important DOM Methods
The chapter covers six major methods for selecting HTML elements:
getElementById()getElementsByClassName()getElementsByName()getElementsByTagName()querySelector()querySelectorAll()
getElementById()
This method finds an element using its unique ID.
Syntax
document.getElementById("id");
Example
<!DOCTYPE html>
<html>
<body>
<h2>Web Designing</h2>
<p id="web">
Class 9
</p>
<script>
const paragraph =
document.getElementById("web");
console.log(paragraph);
</script>
</body>
</html>
getElementsByClassName()
This method returns elements having a particular class name.
Syntax
document.getElementsByClassName("className");
Example
<div class="web">
Class
</div>
<div class="web">
9
</div>
<div class="web">
Web Designing
</div>
<script>
const elements =
document.getElementsByClassName("web");
console.log(elements);
</script>
getElementsByName()
This method returns elements having a particular name attribute.
Syntax
document.getElementsByName("name");
Example
<input
type="text"
name="web">
<input
type="number"
name="web">
<script>
const inputs =
document.getElementsByName("web");
console.log(inputs);
</script>
getElementsByTagName()
This method selects elements according to their tag name.
Syntax
document.getElementsByTagName("tagName");
Example
<p>HTML</p>
<p>CSS</p>
<p>JavaScript</p>
<script>
const paragraphs =
document.getElementsByTagName("p");
console.log(paragraphs);
</script>
querySelector()
querySelector() returns the first element matching a CSS selector.
Syntax
document.querySelector("selector");
Example:
<div class="web">
Web Technology
</div>
<p id="para">
Class 9
</p>
<script>
const div =
document.querySelector(".web");
const paragraph =
document.querySelector("#para");
</script>
querySelectorAll()
querySelectorAll() returns all elements matching a CSS selector.
Syntax
document.querySelectorAll("selector");
Example:
<div class="web">HTML</div>
<div class="web">CSS</div>
<div class="web">JavaScript</div>
<script>
const elements =
document.querySelectorAll(".web");
console.log(elements);
</script>
Difference Between querySelector() and querySelectorAll()
querySelector() | querySelectorAll() |
|---|---|
| Returns first matching element. | Returns all matching elements. |
Returns one element or null. | Returns a NodeList. |
| Uses CSS selector syntax. | Uses CSS selector syntax. |
DOM Document Object
The document object represents the current webpage.
Most DOM operations begin with:
document
Examples:
document.getElementById("title");
document.querySelector(".box");
document.createElement("p");
Finding HTML Elements
| Method | Purpose |
|---|---|
document.getElementById(id) | Find by ID |
document.getElementsByTagName(name) | Find by tag |
document.getElementsByClassName(name) | Find by class |
Changing HTML Elements
Important properties and methods include:
| Property / Method | Purpose |
|---|---|
element.innerHTML | Change HTML content |
element.attribute | Change an attribute |
element.style.property | Change CSS style |
element.setAttribute() | Set an attribute |
Changing HTML Content
Example:
<p id="demo">
Old Text
</p>
<script>
document.getElementById("demo").innerHTML =
"New Text";
</script>
Changing CSS with JavaScript
Example:
document.getElementById("demo").style.color =
"red";
Changing an Attribute
Example:
document
.getElementById("photo")
.setAttribute("src", "new-image.jpg");
Adding and Removing Elements
Important DOM methods include:
createElement()appendChild()removeChild()replaceChild()
Create an Element
var paragraph =
document.createElement("p");
Add an Element
document.body.appendChild(paragraph);
Add Event Handler
Example:
document.getElementById("button").onclick =
function () {
alert("Button clicked!");
};
DOM Document Properties
Examples discussed in the chapter include:
document.bodydocument.headdocument.formsdocument.imagesdocument.linksdocument.scriptsdocument.titledocument.URLdocument.cookiedocument.doctypedocument.readyStatedocument.lastModified
Selecting Elements by ID
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select by ID</title>
</head>
<body>
<p id="mark">
This is a paragraph.
</p>
<p>
This is another paragraph.
</p>
<script>
var match =
document.getElementById("mark");
match.style.backgroundColor =
"yellow";
</script>
</body>
</html>
Selecting Elements by Class Name
<p class="test">
First Paragraph
</p>
<div class="test">
Second Element
</div>
<script>
var matches =
document.getElementsByClassName("test");
document.write(
"Number of selected elements: " +
matches.length
);
</script>
Selecting Elements by Tag Name
<p>First Paragraph</p>
<p>Second Paragraph</p>
<script>
var paragraphs =
document.getElementsByTagName("p");
document.write(
"Number of paragraphs: " +
paragraphs.length
);
</script>
Selecting Elements with CSS Selectors
<ul>
<li>Bread</li>
<li class="tick">
Coffee
</li>
<li>Pineapple Cake</li>
</ul>
<script>
var items =
document.querySelectorAll("ul li");
for (var item of items) {
document.write(
item.innerHTML + "<br>"
);
}
</script>
DOM Node List
A node is an item in the DOM tree.
Examples of nodes include:
- Element Nodes
- Text Nodes
- Comment Nodes
- Document Nodes
- Attribute-related nodes
Some DOM methods return collections such as:
NodeList
For example:
document.querySelectorAll("p");
returns a NodeList.
JavaScript Control Flow
Control flow describes the order in which program statements are executed.
Normally, code executes from top to bottom.
Control flow can be changed using:
- Conditional Statements
- Loops
- Functions
The chapter covers:
ifswitchdo...whilewhilefor
Conditional Statements
Conditional statements allow a program to make decisions.
if Statement
The if statement executes code when a condition is true.
Syntax
if (condition) {
// Code executed if true
}
Example
var age = 20;
if (age > 18) {
document.write(
"Qualifies for driving."
);
}
if...else
An else block can be used when the condition is false.
var age = 16;
if (age >= 18) {
document.write("Adult");
} else {
document.write("Minor");
}
switch Statement
The switch statement selects one block of code from several alternatives.
Syntax
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
Switch Example
var grade = "A";
switch (grade) {
case "A":
document.write("Good Job");
break;
case "B":
document.write("Pretty Good");
break;
case "C":
document.write("Passed");
break;
case "D":
document.write("Not So Good");
break;
default:
document.write("Unknown Grade");
}
JavaScript Loops
A loop repeats a block of code.
The chapter covers:
do...whilewhilefor
do...while Loop
A do...while loop checks the condition after executing the loop body.
Therefore, it executes at least once.
Syntax
do {
// statements
} while (condition);
Example
var count = 0;
do {
document.write(
"Current Count: " +
count +
"<br>"
);
count++;
} while (count < 5);
while Loop
A while loop repeats as long as its condition is true.
Syntax
while (condition) {
// statements
}
Example
var count = 0;
while (count < 5) {
document.write(
"Current Count: " +
count +
"<br>"
);
count++;
}
for Loop
The for loop is a compact looping structure.
It contains:
- Initialization
- Condition
- Iteration
Syntax
for (
initialization;
condition;
iteration
) {
// statements
}
Example
for (
var count = 0;
count < 10;
count++
) {
document.write(
"Current Count: " +
count +
"<br>"
);
}
Difference Between Loops
| Loop | Condition Check | Important Feature |
|---|---|---|
while | Before execution | May execute zero times |
do...while | After execution | Executes at least once |
for | Before each iteration | Compact counter-based loop |
JavaScript Functions
A function is a reusable block of code designed to perform a specific task.
Functions can be called many times.
Advantages of Functions
- Code Reusability
- Less Repetition
- Smaller Programs
- Better Organization
- Better Readability
- Easier Maintenance
Function Syntax
function functionName() {
// code
}
Function Example
function greet() {
console.log(
"Hello There!"
);
}
Calling a Function
A function runs when it is called.
greet();
Complete Example
function greet() {
console.log(
"Hello There!"
);
}
greet();
Function Parameters
Parameters allow values to be supplied to a function.
Example:
function greet(name) {
console.log(
"Hello " + name
);
}
greet("Ram");
Here:
name → Parameter
"Ram" → Argument
Function Return
The return statement sends a result back from a function.
Example:
function add(a, b) {
return a + b;
}
var result =
add(5, 3);
console.log(result);
Output:
8
Function with User Input
function add(a, b) {
return a + b;
}
let number1 =
parseFloat(
prompt(
"Enter first number:"
)
);
let number2 =
parseFloat(
prompt(
"Enter second number:"
)
);
let result =
add(
number1,
number2
);
console.log(
"The sum is " +
result
);
Function Expression
A function can also be stored in a variable.
Example:
let square =
function (num) {
return num * num;
};
console.log(
square(4)
);
Output:
16
JavaScript Dialog Boxes
The chapter discusses three common browser dialog functions:
alert()prompt()confirm()
alert()
The alert() method displays a message with an OK button.
Syntax
alert("Message");
Example
<button onclick="showAlert()">
Click Me
</button>
<script>
function showAlert() {
alert(
"This is an alert dialog box."
);
}
</script>
prompt()
The prompt() method displays a dialog asking the user to enter a value.
Syntax
prompt(
"Message",
"Default Value"
);
Example
var name =
prompt(
"Enter your name:",
"Student"
);
document.write(name);
confirm()
The confirm() method displays:
- OK
- Cancel
It returns:
OK → true
Cancel → false
Example
function getConfirmation() {
var result =
confirm(
"Do you want to continue?"
);
if (result === true) {
document.write(
"User wants to continue!"
);
} else {
document.write(
"User does not want to continue!"
);
}
}
Difference Between Alert, Prompt and Confirm
| Method | Purpose | Returns |
|---|---|---|
alert() | Display a message | No useful user value |
prompt() | Ask user for input | Text or null |
confirm() | Ask for confirmation | true or false |
JavaScript Objects
A JavaScript object stores related properties and methods.
For example, a student object might contain:
- Name
- Age
- Class
Objects can represent real-world entities such as:
- Car
- Pen
- Bike
- Student
- Employee
- Computer
Object Properties and Methods
An object may contain:
Properties
Data stored in the object.
Example:
name
age
salary
Methods
Functions associated with an object.
Creating JavaScript Objects
The source discusses three common ways:
- Object Literal
new Object()- Constructor Function
1. Object Literal
An object literal uses curly braces {}.
Syntax
var objectName = {
property1: value1,
property2: value2
};
Example
var employee = {
id: 102,
name: "Shyam Kumar",
salary: 40000
};
document.write(
employee.id +
" " +
employee.name +
" " +
employee.salary
);
2. Creating an Object with new Object()
Example:
var employee =
new Object();
employee.id =
101;
employee.name =
"Ravi Malik";
employee.salary =
50000;
document.write(
employee.id +
" " +
employee.name +
" " +
employee.salary
);
3. Object Constructor
A constructor function can be used to create multiple similar objects.
Example:
function Employee(
id,
name,
salary
) {
this.id =
id;
this.name =
name;
this.salary =
salary;
}
var employee =
new Employee(
103,
"Vimal Jaiswal",
30000
);
document.write(
employee.id +
" " +
employee.name +
" " +
employee.salary
);
Common JavaScript Object Methods
The chapter lists several built-in Object methods.
| Method | Purpose |
|---|---|
Object.assign() | Copies properties between objects |
Object.create() | Creates an object using a prototype |
Object.defineProperty() | Defines or changes a property |
Object.defineProperties() | Defines multiple properties |
Object.entries() | Returns key-value pairs |
Object.freeze() | Prevents certain changes to an object |
Object.getOwnPropertyDescriptor() | Gets a property descriptor |
Object.getOwnPropertyDescriptors() | Gets descriptors of properties |
Object.getOwnPropertyNames() | Returns property names |
Object.getOwnPropertySymbols() | Returns symbol properties |
Object.getPrototypeOf() | Returns an object’s prototype |
Object.is() | Compares two values |
Object.isExtensible() | Checks whether properties can be added |
Object.isFrozen() | Checks whether an object is frozen |
Object.isSealed() | Checks whether an object is sealed |
Object.keys() | Returns property names |
Object.preventExtensions() | Prevents new properties |
Object.seal() | Prevents adding/removing properties |
Object.setPrototypeOf() | Sets an object’s prototype |
Object.values() | Returns property values |
Quick Revision
JavaScript
JavaScript is used to add interactivity and programming behaviour to webpages.
Ways to Add JavaScript
- Embedded JavaScript
- Inline JavaScript
- External JavaScript
Script Element
<script>
// JavaScript code
</script>
External JavaScript
<script src="script.js"></script>
Common Data Types
Primitive Types Covered in the Chapter
- String
- Number
- Boolean
- Undefined
- Null
Reference Types Covered
- Object
- Array
- RegExp
Variable
var name = "Ram";
Global Variable
Declared outside a function.
Local Variable
Declared inside a function.
DOM
DOM stands for:
Document Object Model
Important DOM Methods
document.getElementById()
document.getElementsByClassName()
document.getElementsByName()
document.getElementsByTagName()
document.querySelector()
document.querySelectorAll()
If Statement
if (condition) {
// code
}
Switch Statement
switch (value) {
case 1:
break;
default:
break;
}
While Loop
while (condition) {
// code
}
Do While Loop
do {
// code
} while (condition);
For Loop
for (
initialization;
condition;
iteration
) {
// code
}
Function
function greet() {
console.log(
"Hello"
);
}
Alert
alert("Hello");
Prompt
prompt(
"Enter your name:"
);
Confirm
confirm(
"Are you sure?"
);
Object Literal
var student = {
name: "Ram",
age: 15
};
Important Exam Points
- JavaScript is used to make webpages interactive.
- JavaScript was introduced in 1995.
- Brendan Eich created JavaScript.
- JavaScript was initially associated with Netscape.
- JavaScript was later standardized as ECMAScript.
- JavaScript can run in a web browser.
- JavaScript can manipulate HTML and CSS.
- JavaScript can respond to events.
- JavaScript can interact with the DOM.
- JavaScript may be embedded, inline, or external.
- External JavaScript files use the
.jsextension. - External JavaScript is connected using the
srcattribute. - JavaScript variables store values.
- JavaScript is dynamically typed.
- The chapter discusses primitive and non-primitive data types.
- Strings store text.
- Numbers store numeric values.
- Boolean values are
trueorfalse. undefinedrepresents an unassigned value.nullrepresents an intentionally empty value.- Arrays store collections of values.
- Objects store related properties and methods.
- JavaScript variable names are case-sensitive.
- Variable names should not start with a digit.
- DOM stands for Document Object Model.
getElementById()selects an element by ID.getElementsByClassName()selects elements by class.getElementsByTagName()selects elements by tag.querySelector()returns the first matching element.querySelectorAll()returns all matching elements.- JavaScript can change HTML content through the DOM.
- JavaScript can change CSS styles through the DOM.
- Control flow includes conditional statements and loops.
ifexecutes code when a condition is true.switchselects among several possible cases.do...whileexecutes at least once.whilerepeats while a condition is true.foris commonly used for counter-based loops.- Functions provide reusable blocks of code.
- Function parameters receive input values.
returnsends a value back from a function.alert()displays a message.prompt()accepts user input.confirm()returnstrueorfalse.- Objects can be created using object literals.
- Objects can also be created with
new Object(). - Constructor functions can create multiple similar objects.
Discussion
Share a helpful question, idea, or explanation with other students.