JavaScript is a programming language used to make web pages interactive.
It can:
● Update content dynamically.
● Respond to user actions (clicks, typing, etc.).
● Communicate with servers (fetch data).
● Add animations and effects.
How to Use JavaScript?
JavaScript can be used in three main ways:
1️⃣ Inline JavaScript (inside an HTML element)
2️⃣ Internal JavaScript (inside a <script> tag in HTML)
3️⃣ External JavaScript (linked via a .js file)
Let’s go through each method with examples. 👇
1️⃣ Inline JavaScript (Directly Inside an HTML Element)
Inline JavaScript is added inside an HTML element using the onclick or
other event attributes.
✅ Example:
<button onclick="alert('Hello!')">Click Me</button>
📌 When you click the button, an alert pops up saying "Hello!".
🔴 Disadvantages:
● Not recommended for large projects because it makes HTML messy.
● Harder to debug and maintain.
2️⃣ Internal JavaScript (Inside a <script> Tag)
JavaScript code can be placed inside a <script> tag within an HTML
file.
✅ Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Internal JavaScript</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("title").innerHTML = "JavaScript
Changed Me!";
}
</script>
</body>
</html>
📌 Clicking the button updates the heading text.
3️⃣ External JavaScript (Using a .js File)
For larger projects, it's best to keep JavaScript in a separate file.
Step 1: Create an HTML file (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<title>External JavaScript</title>
<script src="script.js"></script> <!-- Linking JS file -->
</head>
<body>
<h1 id="title">Hello, World!</h1>
<button onclick="changeText()">Click Me</button>
</body>
</html>
Step 2: Create a JavaScript file (script.js)
function changeText() {
document.getElementById("title").innerHTML = "JavaScript Updated Me!";
}
✅ Advantages of External JavaScript:
✔ Keeps HTML clean and readable.
✔ Easier to maintain and debug.
✔ Reusable across multiple pages.
4️⃣ Running JavaScript in the Browser Console
You can also run JavaScript directly in the browser console.
Steps:
1.Open Google Chrome (or any browser).
2.Right-click on the page → Click Inspect.
3.Go to the Console tab.
4.Type the following code and press Enter:
console.log("Hello from JavaScript!");
✅ The message "Hello from JavaScript!" appears in the console.
JavaScript Variables
What is a Variable?
A variable in JavaScript is a container that stores data. It allows us to reuse and manipulate
values in our program.
Declaring Variables in JavaScript
JavaScript provides three ways to declare variables:
1️⃣ var (old way, avoid using it)
2️⃣ let (modern and recommended)
3️⃣ const (for values that never change)
1️⃣ Using var (Old Way)
✅ var allows redeclaration and reassigning values but has function scope (not block scope).
var name = "John";
console.log(name); // Output: John
OR
name = "Mike"; // Changing value
console.log(name); // Output: Mike
2️⃣ Using let (Modern & Recommended)
✅ let allows reassigning values but not redeclaration in the same scope.
✅ It has block scope, meaning it's only available inside {}.
let age = 25;
console.log(age); // Output: 25
age = 30; // Allowed (reassigning)
console.log(age); // Output: 30
let age = 40; // ❌ Error! (Cannot redeclare `age` in the same scope)
✅ Example of let block scope:
if (true) {
let message = "Hello!";
console.log(message); // Output: Hello!
console.log(message); // ❌ Error! (message is not available outside)
3️⃣ Using const (Constant, Cannot Be Changed)
✅
✅ Must be initialized at the time of declaration.
const means constant (cannot be reassigned).
✅ It has block scope, just like let.
const pi = 3.14;
console.log(pi); // Output: 3.14
pi = 3.1415; // ❌ Error! (Cannot change `const` value)
🔹 Good use of const:
Use const for values that should never change:
const daysInWeek = 7;
const website = "https://example.com";
4️⃣ Variable Naming Rules
1. ✅
❌ Use letters, numbers, _, and $ (but cannot start with a number).
✅ Use camelCase for multi-word names (userName, totalAmount).
2. No spaces in variable names.
✅ Avoid reserved keywords (let, var, const, if, else, etc.).
3.
4.
✅ Valid Examples:
let userName = "Alice";
let _price = 100;
let $discount = 10;
❌ Invalid Examples:
let 1stUser = "John"; // ❌ Cannot start with a number
let user name = "Alice"; // ❌ No spaces allowed
let let = 10; // ❌ Cannot use reserved keywords
5️⃣ Summary: When to Use Which Variable Type?
Keyword Can Can Scope Use Case
Reassign? Redeclare?
var ✅ Yes ✅ Yes Function Scope ❌ Avoid using
let ✅ Yes ❌ No Block Scope ✅ Recommended for
variables that change
const ❌ No ❌ No Block Scope ✅ Use for fixed values
6️⃣ Mini Practice
🔹 Guess the output before running the code:
let city = "New York";
console.log(city);
city = "London";
console.log(city);
const country = "USA";
console.log(country);
country = "Canada"; // What will happen here?
console.log(country);
✅ Try it and check the error! 🚀
JavaScript Data Types
What is a Data Type?
A data type in JavaScript defines what kind of value a variable can
hold.
📌 Example:
let age = 25; // Number
let name = "Alice"; // String
let isStudent = true; // Boolean
JavaScript has two main types:
1️⃣ Primitive Data Types (basic values)
2️⃣ Non-Primitive (Reference) Data Types (objects, arrays, functions)
1️⃣ Primitive Data Types (Stored directly in memory)
Data Type Example
Number let x = 10;
String let name = "John";
Boolean let isStudent = true;
Undefined let value;
Null let data = null;
BigInt let bigNum = 12345678901234567890n;
Symbol let id = Symbol("id");
1.1 Number 🔢
Used for both integers and decimals.
let a = 10;
let b = 3.14;
console.log(typeof a); // Output: number
console.log(typeof b); // Output: number
1.2 String 📝
Text values, written in single or double quotes.
let firstName = "Alice";
let lastName = 'Smith';
console.log(typeof firstName); // Output: string
✅ Template Literals (Using backticks ``)
let name = "John";
let message = `Hello, ${name}!`;
console.log(message); // Output: Hello, John!
1.3 Boolean 🔘
Only true or false values.
let isAdult = true;
let hasLicense = false;
console.log(typeof isAdult); // Output: boolean
1.4 Undefined ❓
A variable declared but not assigned a value.
let x;
console.log(x); // Output: undefined
1.5 Null 🚫
Represents an empty or unknown value.
let data = null;
console.log(data); // Output: null
1.6 BigInt 🏦
Used for very large numbers (n at the end).
let bigNumber = 12345678901234567890n;
console.log(typeof bigNumber); // Output: bigint
1.7 Symbol 🔑
A unique identifier, mostly used in advanced applications.
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // Output: false
2️⃣ Non-Primitive (Reference) Data Types
These store references (memory locations) instead of actual values.
Data Type Example
Object { name: "John", age: 25 }
Array [1, 2, 3, 4, 5]
Function function sayHello() { console.log("Hello"); }
2.1 Object 🏠 (Stores key-value pairs)
let person = { name: "Alice", age: 25 };
console.log(person.name); // Output: Alice
2.2 Array 📋 (Holds multiple values)
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Output: Red
2.3 Function ⚙️ (Reusable block of code)
function greet() {
return "Hello, World!";
}
console.log(greet()); // Output: Hello, World!
3️⃣ Checking Data Types
Use the typeof operator to check a variable’s type.
console.log(typeof 42); // number
console.log(typeof "Hello"); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (this is a known JavaScript bug!)
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof function(){}); // function
4️⃣ Type Conversion
✅ String to Number:
let str = "123";
let num = Number(str);
console.log(num); // Output: 123
console.log(typeof num); // Output: number
✅ Number to String:
let num = 456;
let str = String(num);
console.log(str); // Output: "456"
console.log(typeof str); // Output: string
✅ Boolean to Number:
console.log(Number(true)); // Output: 1
console.log(Number(false)); // Output: 0
5️⃣ Summary Table
Data Type Example typeof Result
Number let x = 10; "number"
String let name = "Alice"; "string"
Boolean let isTrue = true; "boolean"
Undefined let y; "undefined"
Null let z = null; "object" (JavaScript bug)
BigInt let big = 123n; "bigint"
Symbol let id = Symbol("id"); "symbol"
Object let person = {name: "John"}; "object"
Array let arr = [1, 2, 3]; "object"
Function function test() {} "function"
6️⃣ Mini Challenge 🚀
🔹 What will be the output?
console.log(typeof []);
console.log(typeof NaN);
console.log(typeof null);
console.log(typeof function(){});
console.log(typeof 100n);
👉 Try running it in the browser console!
JavaScript Operators
What is an Operator?
An operator is a symbol that performs operations on variables or values.
📌 Example:
let sum = 5 + 3; // '+' is an operator
console.log(sum); // Output: 8
JavaScript has different types of operators:
1️⃣ Arithmetic Operators
2️⃣ Assignment Operators
3️⃣ Comparison Operators
4️⃣ Logical Operators
5️⃣ Bitwise Operators
6️⃣ Ternary Operator
7️⃣ Type Operators
1️⃣ Arithmetic Operators 🔢 (Used for mathematical calculations)
Operator Description Example
+ Addition 5 + 3 // 8
- Subtraction 10 - 4 // 6
* Multiplication 2 * 3 // 6
/ Division 10 / 2 // 5
% Modulus (Remainder) 10 % 3 // 1
** Exponentiation (Power) 2 ** 3 // 8
++ Increment let a = 5; a++ // 6
-- Decrement let b = 5; b-- // 4
✅ Example:
let x = 10;
let y = 5;
console.log(x + y); // Output: 15
console.log(x - y); // Output: 5
console.log(x * y); // Output: 50
console.log(x / y); // Output: 2
console.log(x % y); // Output: 0
console.log(x ** y); // Output: 100000
2️⃣ Assignment Operators (Used to assign values to variables)
Operator Description Example
= Assign value x = 5
+= Add & Assign x += 3 // x = x + 3
-= Subtract & Assign x -= 2 // x = x - 2
*= Multiply & Assign x *= 4 // x = x * 4
/= Divide & Assign x /= 2 // x = x / 2
%= Modulus & Assign x %= 3 // x = x % 3
✅ Example:
let a = 10;
a += 5; // a = a + 5 (Now a = 15)
a *= 2; // a = a * 2 (Now a = 30)
console.log(a); // Output: 30
3️⃣ Comparison Operators ⚖️ (Used to compare values)
Operator Description Example Output
== Equal to 5 == "5" true
=== Strictly Equal 5 === "5" false
!= Not Equal 5 != 3 true
!== Strictly Not Equal 5 !== "5" true
> Greater Than 10 > 5 true
< Less Than 10 < 5 false
>= Greater Than or Equal 5 >= 5 true
<= Less Than or Equal 4 <= 3 false
✅ Example:
console.log(5 == "5"); // Output: true (loose comparison)
console.log(5 === "5"); // Output: false (strict comparison)
console.log(10 > 5); // Output: true
console.log(10 <= 5); // Output: false
4️⃣ Ternary Operator (Shorthand for if-else)
The ternary operator is a shortcut for if-else statements.
✅ Syntax:
condition ? trueResult : falseResult;
✅ Example:
let age = 18;
let message = (age >= 18) ? "You are an adult" : "You are a minor";
console.log(message); // Output: You are an adult
Mini Quiz Challenge
Guess the output before running the code:
console.log(10 + "5");
console.log("5" - 2);
console.log(3 > 2 > 1);
console.log(!!"false");
console.log(5 == "5");
console.log(5 === "5");
✔ Try it in the browser console!
JavaScript Conditional Statements
What is a Conditional Statement?
A conditional statement allows you to make decisions in your program
based on certain conditions. If the condition is true, a block of code
will run. If the condition is false, the code block will be skipped or
an alternate block of code will run.
1️⃣ if Statement
The if statement evaluates a condition and executes a block of code if
the condition is true.
Syntax:
if (condition) {
// Code to run if condition is true
}
Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
// Output: You are an adult.
2️⃣ if-else Statement
The if-else statement allows you to specify an alternative block of
code to run when the condition is false.
Syntax:
if (condition) {
// Code to run if condition is true
} else {
// Code to run if condition is false
}
Example:
let age = 15;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// Output: You are a minor.
3️⃣ else if Statement
The else if statement allows you to check multiple conditions. If the
first condition is false, it checks the second condition, and so on.
Syntax:
if (condition1) {
// Code to run if condition1 is true
} else if (condition2) {
// Code to run if condition2 is true
} else {
// Code to run if none of the above conditions are true
}
Example:
let score = 85;
if (score >= 90) {
console.log("You got an A.");
} else if (score >= 80) {
console.log("You got a B.");
} else {
console.log("You got a C.");
}
// Output: You got a B.
4️⃣ switch Statement
The switch statement is an alternative to multiple if-else statements.
It checks a value against a series of case options and executes the
corresponding block of code.
Syntax:
switch (expression) {
case value1:
// Code to run if expression === value1
break;
case value2:
// Code to run if expression === value2
break;
default:
// Code to run if expression doesn't match any case
}
Example:
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
// Output: Wednesday
5️⃣ Ternary Operator (Shorthand for if-else)
The ternary operator is a shorter way to write an if-else statement.
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
Example:
let age = 20;
let result = (age >= 18) ? "You are an adult." : "You are a minor.";
console.log(result);
// Output: You are an adult.
6️⃣ Nested if Statements
You can nest an if statement inside another if statement for more
complex conditions.
Example:
let age = 25;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive.");
} else {
console.log("You need a driver's license.");
}
} else {
console.log("You are too young to drive.");
}
// Output: You can drive.
7️⃣ if with Logical Operators
You can combine multiple conditions using logical operators like &&
(AND) and || (OR).
Example:
let age = 20;
let hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("You can enter the event.");
} else {
console.log("You cannot enter the event.");
}
// Output: You can enter the event.
8️⃣ switch with Multiple Cases
You can use multiple case labels for the same block of code.
Example:
let fruit = "apple";
switch (fruit) {
case "apple":
case "banana":
console.log("It's a fruit.");
break;
case "carrot":
console.log("It's a vegetable.");
break;
default:
console.log("Unknown item.");
}
// Output: It's a fruit.
Output using HTML:
<!DOCTYPE html>
<html>
<head>
<title>Switch Statement Output</title>
</head>
<body>
<h2>Item Checker</h2>
<div id="output"></div>
<script>
let fruit = "apple";
let message = "";
switch (fruit) {
case "apple":
case "banana":
message = "It's a fruit.";
break;
case "carrot":
message = "It's a vegetable.";
break;
default:
message = "Unknown item.";
}
document.getElementById("output").innerHTML = message;
</script>
</body>
</html>
Summary of Conditional Statements
Statement Description
if Executes code if a condition is true.
else Executes code if the if condition is false.
else if Checks for additional conditions if the previous ones are false.
switch Compares a value against multiple possible cases.
Ternary A shorthand for if-else statements.
Mini Challenge: What will be the output?
Problem 1: Nested Conditions
let age = 20;
let hasID = true;
if (age >= 18) {
if (hasID) {
console.log("Access granted.");
} else {
console.log("ID required.");
}
} else {
console.log("Underage.");
}
Output:
Access granted.
Since age >= 18 and hasID is true, both conditions are satisfied.
Problem 2: Using switch with Multiple Cases
let grade = "B";
switch (grade) {
case "A":
console.log("Excellent!");
break;
case "B":
case "C":
console.log("Good job.");
break;
case "D":
console.log("You passed.");
break;
case "F":
console.log("Try again.");
break;
default:
console.log("Invalid grade.");
}
Output:
Good job.
Both "B" and "C" cases trigger the same output.
Problem 3: Logical Operators
let temp = 35;
let isRaining = false;
if (temp > 30 && !isRaining) {
console.log("Go to the beach.");
} else if (temp > 30 && isRaining) {
console.log("Stay indoors.");
} else {
console.log("Go for a walk.");
}
Output:
Go to the beach.
temp > 30 is true and !isRaining is also true.
Problem 4: Complex Conditions with else if Ladder
let marks = 75;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 80) {
console.log("Grade: B");
} else if (marks >= 70) {
console.log("Grade: C");
} else if (marks >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
Output:
Grade: C
marks = 75, which falls in the >= 70 range.
JavaScript Loops
What is a Loop?
A loop is used to repeatedly execute a block of code as long as a specified condition is true. It
helps automate repetitive tasks and save time in your code. JavaScript provides several types
of loops.
1️⃣ for Loop
The for loop is used when you know how many times you want to execute a block of code.
Syntax:
for (initialization; condition; increment) {
// Code to run on each iteration
}
Explanation:
● Initialization: Sets up the initial condition (usually a counter variable).
● Condition: The loop will continue as long as this condition is true.
● Increment/Decrement: Updates the loop variable after each iteration.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0 1 2 3 4
In this example:
● The loop starts with i = 0.
● It checks if i < 5. If true, it runs the code inside the loop.
● After each loop, i is incremented by 1 (i++).
2️⃣ while Loop
The while loop is used when you don't know exactly how many times you need to execute the
code, but you know the condition to stop.
Syntax:
while (condition) {
// Code to run as long as condition is true
}
Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0 1 2 3 4
Here:
● The loop runs as long as i < 5.
● After each iteration, i is incremented (i++).
3️⃣ do...while Loop
The do...while loop is similar to the while loop, but the code inside the loop is always
executed at least once before the condition is checked.
Syntax:
do {
// Code to run
} while (condition);
Example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0 1 2 3 4
In this case:
● The code inside the loop runs first, and then the condition is checked.
● The loop continues while i < 5.
4️⃣ for...in Loop
The for...in loop is used to iterate over the properties of an object.
Syntax:
for (let key in object) {
// Code to run for each key in the object
}
Example:
let person = { name: "Alice", age: 25, city: "New York" };
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 25
// city: New York
Here:
● The loop iterates over each key in the person object.
● person[key] accesses the value associated with each key.
5️⃣ for...of Loop
The for...of loop is used to iterate over the values of an iterable object like an array or
string.
Syntax:
for (let value of iterable) {
// Code to run for each value in the iterable
}
Example:
let colors = ["Red", "Green", "Blue"];
for (let color of colors) {
console.log(color);
}
// Output:
// Red
// Green
// Blue
Here:
● The loop iterates over each value in the colors array.
6️⃣ Breaking and Continuing in Loops
You can control the flow of loops using the break and continue keywords.
break
The break statement is used to exit the loop early, even if the condition hasn't been met.
Example:
for (let i = 0; i < 5; i++) {
if (i === 3) {
break; // Exit the loop when i is 3
}
console.log(i);
}
// Output: 0 1 2
continue
The continue statement skips the current iteration and moves to the next one.
Example:
for (let i = 0; i < 5; i++) {
if (i === 3) {
continue; // Skip when i is 3
}
console.log(i);
}
// Output: 0 1 2 4
7️⃣ Nested Loops
You can use loops inside other loops, known as nested loops.
Example:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i = ${i}, j = ${j}`);
}
}
// Output:
// i = 1, j = 1
// i = 1, j = 2
// i = 1, j = 3
// i = 2, j = 1
// i = 2, j = 2
// i = 2, j = 3
// i = 3, j = 1
// i = 3, j = 2
// i = 3, j = 3
In this example:
● The outer loop runs 3 times, and for each iteration, the inner loop also runs 3 times.
8️⃣ Infinite Loop
An infinite loop runs forever unless it's broken by some condition (or manually stopped).
Example:
while (true) {
console.log("This will run forever...");
// To stop, you need to manually exit or use a break condition.
}
Warning: Infinite loops can cause your browser or program to freeze!
Mini Quiz Challenge
🔹 What will be the output of this code?
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
console.log("Done");
✔ Try it out in the browser console!
JavaScript Functions
Functions help in reusing code.
Function with Parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
Arrow Functions (Modern)
const add = (a, b) => a + b;
console.log(add(3, 7)); // 10
Arrays in JavaScript
Creating an Array
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Apple
console.log(fruits.length); // 3
Adding & Removing Items
fruits.push("Mango"); // Add at end
fruits.pop(); // Remove last item
fruits.unshift("Lemon"); // Add at beginning
fruits.shift(); // Remove first item
Objects in JavaScript
Objects store key-value pairs.
Creating an Object
let person = {
name: "Alice",
age: 25,
greet: function() {
console.log("Hello, " + this.name);
}
};
console.log(person.name); // Alice
person.greet();
DOM Manipulation
The Document Object Model (DOM) represents an HTML document as a tree structure.
JavaScript can be used to manipulate the DOM to change content, style, and structure dynamically.
JavaScript DOM manipulation allows dynamic content updates without reloading the page.
Example:
HTML:
<h1 id="title">Hello, World!</h1>
<button onclick="changeText()">Click Me</button>
JavaScript:
function changeText() {
document.getElementById("title").innerHTML = "JavaScript Changed Me!";
}
📌 Clicking the button changes the text.
1. Selecting Elements
JavaScript provides multiple ways to select elements from the DOM.
1.1 Using getElementById()
Selects an element by its id.
let heading = document.getElementById("title");
heading.innerHTML = "New Heading";
1.2 Using getElementsByClassName()
Selects elements by class name (returns an array-like collection).
let items = document.getElementsByClassName("item");
items[0].style.color = "red"; // Changes the first item to red
1.3 Using getElementsByTagName()
Selects elements by tag name.
let paragraphs = document.getElementsByTagName("p");
paragraphs[0].style.fontSize = "20px"; // Changes first paragraph size
1.4 Using querySelector()
Selects the first matching element using a CSS selector.
let firstItem = document.querySelector(".item");
firstItem.style.backgroundColor = "yellow";
1.5 Using querySelectorAll()
Selects all matching elements.
let allItems = document.querySelectorAll(".item");
allItems.forEach(item => item.style.color = "blue");
2. Changing Content
2.1 Using innerHTML
Changes the HTML content inside an element.
document.getElementById("title").innerHTML = "New Text Here!";
2.2 Using textContent
Changes only the text (ignores HTML tags inside).
document.getElementById("title").textContent = "Plain Text Only";
2.3 Using innerText
Similar to textContent but respects styling.
document.getElementById("title").innerText = "New Heading";
3. Changing Styles
You can modify an element’s style using JavaScript.
Example: Changing Colors
document.getElementById("title").style.color = "red";
Example: Changing Background
document.getElementById("title").style.backgroundColor = "lightblue";
Example: Changing Font Size
document.getElementById("title").style.fontSize = "30px";
📌 Best Practice: Use CSS classes instead of direct styling.
document.getElementById("title").classList.add("highlight");
🔹 CSS:
.highlight {
color: white;
background-color: black;
padding: 10px;
4. Adding & Removing Elements
4.1 Creating New Elements
let newElement = document.createElement("p");
newElement.innerText = "This is a new paragraph!";
document.body.appendChild(newElement);
4.2 Removing Elements
let element = document.getElementById("title");
element.remove();
5. Adding & Removing Classes
5.1 Adding a Class
document.getElementById("title").classList.add("newClass");
5.2 Removing a Class
document.getElementById("title").classList.remove("oldClass");
5.3 Toggling a Class
document.getElementById("title").classList.toggle("darkMode");
6. Handling Events
JavaScript can respond to user interactions.
6.1 Click Event
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
6.2 Mouse Over Event
document.getElementById("title").addEventListener("mouseover", function()
{
this.style.color = "blue";
});
6.3 Key Press Event
document.addEventListener("keydown", function(event) {
console.log("Key pressed:", event.key);
});
JavaScript Events
JavaScript responds to user actions.
Click Event
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
Example (Input Box)
<!DOCTYPE html>
<html>
<head>
<title>Key Press Example</title>
</head>
<body>
<input type="text" id="title" placeholder="Type here..." />
<script>
document.getElementById("title").addEventListener("keydown",
function(event) {
console.log("Key pressed:", event.key);
});
</script>
</body>
</html>
Fetch API (Getting Data from the Internet)
JavaScript can fetch data from APIs.
Fetching Data Example
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
✅ Fetches data from a server and displays it.
Example: Fetch JSON Data
<!DOCTYPE html>
<html>
<head>
<title>Fetch Example</title>
</head>
<body>
<h2>Random User Info</h2>
<button id="loadBtn">Load User</button>
<div id="user"></div>
<script>
document.getElementById("loadBtn").addEventListener("click", function () {
fetch("https://randomuser.me/api/")
.then(response => response.json())
.then(data => {
const user = data.results[0];
document.getElementById("user").innerHTML = `
<p><strong>Name:</strong> ${user.name.first}
${user.name.last}</p>
<p><strong>Email:</strong> ${user.email}</p>
<img src="${user.picture.medium}" alt="User Picture">
`;
})
.catch(error => {
console.error("Error fetching data:", error);
});
});
</script>
</body>
</html>