FWD
Unit I: Objects in JavaScript & Regular Expressions
1. Explain the different types of objects in JavaScript and how objects are
created.
Different Types of Objects in JavaScript & How Objects Are Created
In JavaScript, objects are used to store collections of data and functions. They consist
of properties (key-value pairs) and methods (functions inside objects).
1. Types of Objects in JavaScript
JavaScript objects can be classified into three main categories:
A. User-Defined Objects
These are objects created by the programmer to store and manipulate data.
🔹 Example (Object Literal):
let student = {
name: "John",
age: 21,
course: "JavaScript",
displayInfo: function() {
console.log(this.name + " is learning " +
this.course);
}
};
student.displayInfo(); // Output: John is learning
JavaScript
➡️ Key Features:
● Created using {} (curly braces).
● Properties and methods are defined inside.
● The this keyword refers to the current object.
B. Built-in Objects (Native Objects)
These are predefined objects provided by JavaScript. Some common built-in objects
include:
String Object – Used for string manipulation.
let str = "Hello, JavaScript!";
console.log(str.length); // 18
console.log(str.toUpperCase()); // HELLO, JAVASCRIPT!
1. Array Object – Used to store multiple values in a single variable.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[1]); // Banana
2. Date Object – Used to work with dates and times.
let today = new Date();
console.log(today.toDateString()); // Example: Fri Mar 14
2025
3. Math Object – Provides mathematical constants and functions.
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
4. RegExp Object – Used for pattern matching and text searching.
let regex = /hello/i; // 'i' makes it case-insensitive
console.log(regex.test("Hello, World!")); // true
2. How Objects Are Created in JavaScript
There are multiple ways to create objects in JavaScript.
A. Using Object Literals (Simplest Method)
● The easiest and most commonly used way.
● Defined using {} and contains key-value pairs.
🔹 Example:
let person = {
name: "Alice",
age: 25,
city: "New York"
};
console.log(person.name); // Alice
➡️ Best For:
● Small-scale applications.
● When an object does not need a blueprint/template.
B. Using new Object() Constructor
● The Object constructor is a built-in method to create objects dynamically.
🔹 Example:
let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.year = 2022;
console.log(car.brand); // Toyota
➡️ Best For:
● When objects need to be created dynamically at runtime.
● When working with key-value pairs in a structured manner.
C. Using Constructor Functions
● A constructor function allows creating multiple objects of the same type.
● It follows the blueprint concept of object-oriented programming.
🔹 Example:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
let p1 = new Person("Bob", 30);
let p2 = new Person("Emma", 28);
console.log(p1.name); // Bob
p2.greet(); // Hello, my name is Emma
➡️ Best For:
● When multiple objects of the same type need to be created.
● When objects share similar properties and behaviors.
D. Using Object.create() Method
● Creates an object with an existing object as its prototype.
● Useful for inheritance without defining a constructor function.
🔹 Example:
let animal = {
type: "Mammal",
makeSound: function() {
console.log("Some generic sound");
};
let dog = Object.create(animal);
dog.breed = "Labrador";
dog.makeSound(); // Some generic sound
console.log(dog.type); // Mammal
➡️ Best For:
● When an object needs to inherit properties from another object.
● When using prototype-based inheritance.
Comparison of Object Creation Methods
Method Simplicity Performance Use Case
Object Literal ✅ Simple ✅ Fast Small, static
objects
new Object() ❌ Complex ❌ Slower Rarely used
Constructor 🔄 Moderate ✅ Fast Multiple
Function instances
Object.create 🔄 Moderate ✅ Fast Prototype
() inheritance
ES6 Classes ✅ Modern ✅ Fast Large-scale
applications
2. What is the prototype chain in JavaScript? How does inheritance work using
prototypes?
Prototype Chain in JavaScript &
Inheritance Using Prototypes
JavaScript uses prototypal inheritance, where objects can inherit properties and
methods from other objects. This is achieved through the prototype chain mechanism.
1. What is the Prototype Chain?
A. Definition
● In JavaScript, every object has a hidden internal property called
[[Prototype]], which points to another object, known as its prototype.
● This forms a chain of prototypes, called the prototype chain.
● If a property or method is not found in an object, JavaScript looks up the chain
to find it in its prototype.
B. Understanding the Prototype Chain
🔹 Example (Prototype Chain in Action)
let animal = {
canEat: true
};
let dog = Object.create(animal); // dog inherits from
animal
dog.bark = function() {
console.log("Woof!");
};
console.log(dog.canEat); // true (inherited from animal)
dog.bark(); // Woof!
➡️ How It Works?
1. dog does not have the property canEat.
2. JavaScript searches in dog’s prototype (animal) and finds canEat.
🔹 Visual Representation of Prototype Chain
dog → animal → Object.prototype → null
2. How Inheritance Works Using Prototypes?
JavaScript allows objects to inherit properties and methods through the prototype
chain.
A. Using Object.create() (Simplest Approach)
● The Object.create() method is used to create a new object with a specified
prototype.
🔹 Example:
let vehicle = {
hasWheels: true,
move: function() {
console.log("Moving...");
};
let car = Object.create(vehicle); // car inherits from
vehicle
car.type = "Sedan";
console.log(car.hasWheels); // true (inherited)
car.move(); // Moving...
console.log(car.type); // Sedan
➡️ Best For:
● Creating new objects with an existing object as a prototype.
● Simple one-level inheritance.
B. Using Constructor Functions (Traditional Approach)
● Constructor functions act as blueprints for creating multiple objects.
🔹 Example:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};
let p1 = new Person("Alice", 25);
let p2 = new Person("Bob", 30);
p1.greet(); // Hello, my name is Alice
p2.greet(); // Hello, my name is Bob
➡️ How It Works?
1. The greet() method is not inside p1 or p2.
2. JavaScript looks up the prototype chain and finds greet() inside
Person.prototype.
➡️ Best For:
● When creating multiple objects with shared methods.
● Helps in memory optimization (methods are stored once in the prototype
instead of being duplicated in each object).
C. Using ES6 Classes (Modern Approach)
● ES6 introduced the class syntax, which internally works using prototypes.
🔹 Example:
class Animal {
constructor(name) {
this.name = name;
speak() {
console.log(this.name + " makes a sound");
class Dog extends Animal {
bark() {
console.log(this.name + " says Woof!");
let dog1 = new Dog("Buddy");
dog1.speak(); // Buddy makes a sound
dog1.bark(); // Buddy says Woof!
➡️ How It Works?
1. Dog extends Animal, meaning Dog.prototype is linked to
Animal.prototype.
2. When calling dog1.speak(), JavaScript looks up the prototype chain and finds
speak() inside Animal.
🔹 Visual Representation of Prototype Chain:
dog1 → Dog.prototype → Animal.prototype → Object.prototype
→ null
➡️ Best For:
● Structuring object-oriented JavaScript programs.
● When working with complex object hierarchies.
D. Manually Setting Prototypes (Advanced Use Case)
● We can manually set an object's prototype using Object.setPrototypeOf().
🔹 Example:
let parent = { greet: function() { console.log("Hello!"); }
};
let child = {};
Object.setPrototypeOf(child, parent);
child.greet(); // Hello!
➡️ Best For:
● When dynamically linking objects at runtime.
● Not recommended for performance-sensitive applications.
3. Prototype Chain Depth and Performance
● Shallow Prototype Chain (Best Performance)
○ If an object finds its property quickly, performance is fast.
○ Example: dog.canEat (only one level deep).
● Deep Prototype Chain (Slower Performance)
○ If an object has to search multiple levels, performance slows down.
Example:
car → vehicle → transport → Object.prototype → null
○ Solution: Keep prototypes shallow whenever possible.
4. Key Differences Between Class-Based and
Prototype-Based Inheritance
Feature Prototype-Based Class-Based Inheritance
Inheritance (ES6)
Syntax Uses functions & Uses class and
prototypes extends
Readability Less readable More readable &
structured
Performance Efficient Similar, but better
structure
Complexity Can be confusing Easier to understand
3. What are Regular Expressions in JavaScript? Explain their usage, patterns,
and modifiers with examples.
Regular Expressions in JavaScript
Regular Expressions (RegExp) in JavaScript are patterns used to match, search, and
manipulate strings. They provide powerful ways to handle text processing efficiently.
1. What are Regular Expressions?
A. Definition
● A Regular Expression (RegExp) is a sequence of characters that defines a
search pattern.
● It is mainly used for string validation, searching, replacing, and text
extraction.
B. How to Create a Regular Expression in JavaScript?
● There are two ways to create a regular expression:
🔹 Using Literal Notation (//)
let pattern = /hello/;
🔹 Using RegExp Constructor
let pattern = new RegExp("hello");
➡️ Difference:
● The literal notation (/pattern/) is simpler and preferred for fixed patterns.
● The constructor (new RegExp("pattern")) is useful when the pattern is
dynamic.
2. Usage of Regular Expressions
Regular expressions are used with string methods like:
A. test() – Checks if a pattern exists
let pattern = /world/;
console.log(pattern.test("Hello world!")); // true
console.log(pattern.test("Hello!")); // false
➡️ Returns true if the pattern is found, otherwise false.
B. match() – Returns matches in an array
let text = "The price is $50 and the discount is $10.";
let result = text.match(/\$\d+/g);
console.log(result); // ["$50", "$10"]
➡️ Returns an array of matches ($50 and $10).
C. replace() – Replaces matched text
let text = "Hello World!";
let newText = text.replace(/World/, "JavaScript");
console.log(newText); // "Hello JavaScript!"
➡️ Replaces "World" with "JavaScript".
D. search() – Returns index of the first match
let text = "I love JavaScript!";
console.log(text.search(/JavaScript/)); // 7
➡️ Returns the starting position of "JavaScript" (index 7).
E. split() – Splits a string based on a pattern
let text = "apple,banana,grapes";
let fruits = text.split(/,/);
console.log(fruits); // ["apple", "banana", "grapes"]
➡️ Splits the string using , as a separator.
3. Regular Expression Patterns (Metacharacters)
Regular expressions include special symbols (metacharacters) to match complex
patterns.
Pattern Meaning Example Output
. Matches any /a.c/.test("a true
character except bc")
newline
\d Matches any digit /\d/.test("Ye true
(0-9) ar 2025")
\D Matches /\D/.test("12 false
non-digit 3")
characters
\w Matches word /\w/.test("he true
characters llo_123")
(letters, digits, _)
\W Matches /\W/.test("he true
non-word llo!")
characters
\s Matches /\s/.test("He true
whitespace llo World")
(space, tab)
\S Matches /\S/.test(" false
non-whitespace ")
characters
4. Quantifiers (Repetition Patterns)
Quantifiers specify how many times a character or group should appear.
Quantifier Meaning Example Matches
+ One or more /a+/ "aa", "aaa"
times
* Zero or more /go*/ "g", "go",
times "goo"
? Zero or one time /colou?r/ "color",
"colour"
{n} Exactly n times /\d{4}/ "2024"
{n,} At least n times /\d{2,}/ "99", "12345"
{n,m} Between n and m /\d{2,4}/ "99", "1234"
times
🔹 Example:
let pattern = /\d{2,4}/;
console.log(pattern.test("123")); // true
console.log(pattern.test("1")); // false
5. Modifiers (Flags)
Modifiers change how a regular expression behaves.
Modifier Meaning Example
i Case-insensitive match /hello/i.test("HELL
O") → true
g Global match (find all "abc
matches) abc".match(/abc/g)
→ ["abc", "abc"]
m Multi-line mode "Hello\nWorld".matc
h(/^World/m) →
"World"
🔹 Example:
let pattern = /hello/i;
console.log(pattern.test("HELLO")); // true (case
insensitive)
6. Grouping & Ranges in Regular Expressions
A. Grouping with ()
● Used to create sub-patterns.
🔹 Example (Extract area code from phone number):
let pattern = /\((\d{3})\)/;
let result = "(123) 456-7890".match(pattern);
console.log(result[1]); // "123"
➡️ Extracts "123" from "(123) 456-7890"
B. Character Sets [ ]
● Matches any character inside brackets.
🔹 Example:
let pattern = /[aeiou]/;
console.log(pattern.test("Hello")); // true (contains 'e'
and 'o')
C. Negation [^ ]
● Matches any character except those inside brackets.
🔹 Example:
let pattern = /[^aeiou]/;
console.log(pattern.test("aei")); // false (only vowels)
console.log(pattern.test("bcd")); // true (consonants
present)
7. Advanced Example: Validate an Email
function isValidEmail(email) {
let pattern =
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return pattern.test(email);
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("wrong-email")); // false
➡️ Ensures email follows the format [email protected]
4. Explain type conversion with examples.
2. Type Conversion in JavaScript
JavaScript automatically converts data types when needed. This is known as Type
Conversion. It is categorized into:
1. Implicit Type Conversion (Type Coercion)
2. Explicit Type Conversion (Type Casting)
A. Implicit Type Conversion (Type Coercion)
JavaScript automatically converts values between types when required.
1️⃣ String + Number → String
🔹 Example:
console.log("5" + 2); // "52"
console.log("Hello" + 10); // "Hello10"
➡️ When a string and a number are added (+), JavaScript converts the number to a
string.
2️⃣ Number + Boolean → Number
🔹 Example:
console.log(5 + true); // 6 (true → 1)
console.log(10 + false); // 10 (false → 0)
➡️ Boolean values (true → 1, false → 0) are converted to numbers.
3️⃣ String * Number → Number
🔹 Example:
console.log("10" * 2); // 20
console.log("5" - 1); // 4
console.log("100" / 10); // 10
➡️ For *, -, /, JavaScript converts the string to a number.
4️⃣ Null & Undefined in Arithmetic Operations
🔹 Example:
console.log(null + 5); // 5 (null → 0)
console.log(undefined + 5); // NaN (undefined → NaN)
➡️ null is treated as 0, but undefined results in NaN.
B. Explicit Type Conversion (Type Casting)
To manually convert data types, JavaScript provides built-in functions.
1️⃣ Convert to String (String(), toString())
🔹 Example:
let num = 123;
console.log(String(num)); // "123"
console.log(num.toString()); // "123"
2️⃣ Convert to Number (Number(), parseInt(), parseFloat())
🔹 Example:
console.log(Number("123")); // 123
console.log(parseInt("123.45")); // 123
console.log(parseFloat("123.45")); // 123.45
console.log(Number("Hello")); // NaN
➡️ parseInt() removes decimals, parseFloat() keeps them.
3️⃣ Convert to Boolean (Boolean())
🔹 Example:
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true
console.log(Boolean("")); // false
console.log(Boolean("Hello")); // true
➡️ Falsy values (0, "", null, undefined, NaN) return false, everything else is
true.
C. Special Cases in Type Conversion
1️⃣ + Operator with Mixed Types
🔹 Example:
console.log(1 + "2"); // "12"
console.log("5" + 3 + 2); // "532"
console.log(5 + 3 + "2"); // "82"
➡️ Numbers are added first, but if a string appears, all values convert to strings.
2️⃣ == vs === in Type Conversion
🔹 Example:
console.log(5 == "5"); // true (Type conversion happens)
console.log(5 === "5"); // false (Strict comparison, no
conversion)
➡️ == allows type coercion, but === requires exact type matching.
Unit II: Event Handling & Document Object Model (DOM)
1. What are JavaScript events? Explain event flow, including event bubbling and
event capturing.
JavaScript Events & Event Flow
(Bubbling & Capturing)
1. What are JavaScript Events?
An event in JavaScript is an action or occurrence detected by the browser. Events
occur when a user interacts with a web page (e.g., clicking a button, pressing a key, or
resizing a window). JavaScript allows developers to handle these events using event
listeners.
Common JavaScript Events
Event Description
click Occurs when an element is clicked
mouseover Triggered when the mouse moves over an element
mouseout Triggered when the mouse leaves an element
keydown Triggered when a key is pressed
keyup Triggered when a key is released
submit Occurs when a form is submitted
load Fires when the page finishes loading
resize Fires when the window is resized
🔹 Example: Click Event
document.getElementById("btn").addEventListener("click",
function() {
alert("Button Clicked!");
});
➡️ Triggers an alert when the button with id="btn" is clicked.
2. Event Flow in JavaScript
When an event occurs on a webpage, it follows a flow through the DOM (Document
Object Model). This flow is categorized into two main phases:
1. Event Capturing (Trickling Phase)
2. Event Bubbling
A. Event Capturing (Trickling Phase)
📌 Definition:
● In this phase, the event starts from the root element (document) and trickles
downward to the target element.
● Capturing occurs before bubbling.
🔹 Example:
Consider the following HTML structure:
<div id="parent">
<button id="child">Click Me</button>
</div>
We add event listeners with useCapture = true, which enables capturing.
🔹 JavaScript Code (Event Capturing in Action)
document.getElementById("parent").addEventListener("click",
function() {
console.log("Parent clicked (Capturing)");
}, true); // true → Event Capturing
document.getElementById("child").addEventListener("click",
function() {
console.log("Child clicked");
}, true);
📌 Output (Click on button):
Parent clicked (Capturing)
Child clicked
➡️ The event first reaches the parent, then the child (Top to Bottom).
B. Event Bubbling
📌 Definition:
● In bubbling, the event starts from the target element and moves upward in the
DOM hierarchy.
● Bubbling is the default behavior in JavaScript.
🔹 JavaScript Code (Event Bubbling in Action)
document.getElementById("parent").addEventListener("click",
function() {
console.log("Parent clicked (Bubbling)");
}, false); // false → Event Bubbling
document.getElementById("child").addEventListener("click",
function() {
console.log("Child clicked");
}, false);
📌 Output (Click on button):
Child clicked
Parent clicked (Bubbling)
➡️ The event starts at the child and bubbles up to the parent (Bottom to Top).
3. Stopping Event Propagation
Sometimes, you might want to stop the event from propagating further. JavaScript
provides two methods to control this behavior:
A. event.stopPropagation() – Stops Bubbling or Capturing
🔹 Example:
document.getElementById("child").addEventListener("click",
function(event) {
console.log("Child clicked");
event.stopPropagation(); // Stops bubbling
});
document.getElementById("parent").addEventListener("click",
function() {
console.log("Parent clicked");
});
📌 Output (Click on button):
Child clicked
➡️ The event does not bubble to the parent because of stopPropagation().
B. event.stopImmediatePropagation() – Stops All Event Listeners
● This method stops the event from calling any other listeners attached to the
same element.
🔹 Example:
document.getElementById("child").addEventListener("click",
function(event) {
console.log("First Listener - Child clicked");
event.stopImmediatePropagation(); // Stops further
listeners
});
document.getElementById("child").addEventListener("click",
function() {
console.log("Second Listener - Child clicked");
});
📌 Output (Click on button):
First Listener - Child clicked
➡️ The second listener does not execute because stopImmediatePropagation()
stops all listeners on the same element.
4. Event Delegation
📌 Definition:
● Instead of adding event listeners to multiple child elements, we can add a single
event listener to a parent element and handle events using delegation.
● This is useful for dynamic elements (e.g., buttons created at runtime).
🔹 Example: Handling Multiple Buttons Using Event Delegation
document.getElementById("parent").addEventListener("click",
function(event) {
if (event.target.tagName === "BUTTON") {
console.log("Button Clicked: " +
event.target.textContent);
});
➡️ All buttons inside parent will trigger this listener.
2. What are event listeners in JavaScript? How are they different from event
handlers? Provide examples.
Event Listeners vs Event Handlers in
JavaScript
1. What are Event Listeners in JavaScript?
📌 Definition:
An event listener is a method that waits for a specified event to occur on an element
and then executes a function when the event is triggered.
✔️ It is added using the addEventListener() method.
✔️ It allows multiple functions to be attached to the same event on the same element.
✔️ It provides better control over event propagation (bubbling & capturing).
🔹 Syntax:
element.addEventListener(event, function, useCapture);
Parameter Description
event The event type (e.g., "click", "mouseover")
function The function to execute when the event occurs
useCapture true for event capturing, false (default) for bubbling
🔹 Example: Adding an Event Listener to a Button
document.getElementById("btn").addEventListener("click",
function() {
alert("Button Clicked!");
});
✔️ When the button with id="btn" is clicked, an alert is displayed.
2. What are Event Handlers in JavaScript?
📌 Definition:
An event handler is a property (onEvent) assigned to an element to define a function
that executes when the event occurs.
✔️ It is assigned using element.event = function() { ... }.
✔️ It overwrites any existing event handlers.
✔️ It supports only one function per event per element.
🔹 Syntax:
element.event = function() {
// Code to execute when the event occurs
};
🔹 Example: Using an Event Handler for Click Event
document.getElementById("btn").onclick = function() {
alert("Button Clicked!");
};
✔️ When the button is clicked, an alert appears.
✔️ If a new function is assigned to onclick, the previous function is lost.
3. Differences Between Event Listeners & Event
Handlers
Feature Event Listener Event Handler (onEvent)
(addEventListener)
Multiple Functions ✅ Allows multiple event ❌ Only one function can be
listeners on the same element assigned (overwrites previous
ones)
Removing Events ✅ Can remove specific ❌ Cannot remove handlers
listeners using without setting it to null
removeEventListener()
Event Propagation ✅ Supports event capturing ❌ Does not support event
& bubbling (useCapture propagation control
parameter)
Flexibility ✅ More flexible, supports ❌ Less flexible, only supports
anonymous & named direct assignment
functions
4. Removing an Event Listener
✔️ removeEventListener() is used to remove an event listener.
✔️ The function must be named (cannot remove anonymous functions).
🔹 Example: Removing an Event Listener
function sayHello() {
console.log("Hello!");
}
// Adding event listener
document.getElementById("btn").addEventListener("click",
sayHello);
// Removing event listener
document.getElementById("btn").removeEventListener("click",
sayHello);
✔️ Clicking the button prints "Hello!".
✔️ After removeEventListener() is called, the function is no longer executed.
5. Overwriting Event Handlers
✔️ Only one event handler can be assigned to an event.
✔️ Assigning a new function overwrites the previous handler.
🔹 Example: Overwriting an Event Handler
document.getElementById("btn").onclick = function() {
console.log("First Function");
};
document.getElementById("btn").onclick = function() {
console.log("Second Function");
};
📌 Output (Click on btn):
Second Function
✔️ The first function is overwritten, so only "Second Function" is executed.
6. Using Multiple Event Listeners on the Same Element
✔️ Unlike event handlers, multiple event listeners can exist for the same event.
🔹 Example: Multiple Listeners on One Button
document.getElementById("btn").addEventListener("click",
function() {
console.log("First Event Listener");
});
document.getElementById("btn").addEventListener("click",
function() {
console.log("Second Event Listener");
});
📌 Output (Click on btn):
First Event Listener
Second Event Listener
✔️ Both event listeners execute without overriding each other.
3. Explain the Document Object Model (DOM) and describe its different types
and methods for document manipulation.
Document Object Model (DOM) in
JavaScript
1. What is the Document Object Model (DOM)?
📌 Definition:
The Document Object Model (DOM) is a programming interface for web documents.
It represents the structure of an HTML or XML document as a tree of objects, allowing
JavaScript to interact with and manipulate the document dynamically.
✔️ The DOM treats the entire webpage as a hierarchical tree of elements.
✔️ JavaScript can use the DOM to access, modify, add, or remove elements from a
webpage.
🔹 Example: Simple HTML Page
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="title">Hello, DOM!</h1>
<p class="text">This is a paragraph.</p>
</body>
</html>
✔️ The DOM represents this structure as a tree, where <html> is the root node, and
all other elements are children of it.
2. Types of DOM
JavaScript interacts with different types of DOM structures:
A. Core DOM
✔️ A standard model for all types of structured documents.
✔️ Used in XML and HTML.
B. HTML DOM
✔️ A model specific to HTML documents.
✔️ Provides methods and properties to access and manipulate HTML elements.
C. XML DOM
✔️ Similar to HTML DOM but used for XML documents.
✔️ Works with tree structures, allowing manipulation of XML data.
🔹 Example: HTML DOM vs. XML DOM
<!-- XML DOM Example -->
<books>
<book>
<title>JavaScript Guide</title>
<author>John Doe</author>
</book>
</books>
✔️ XML DOM allows JavaScript to search for <title> inside <book> just like HTML
DOM.
3. Methods for Document Manipulation in DOM
The DOM provides various methods to dynamically change elements, attributes, and
styles.
A. Selecting Elements
JavaScript provides several methods to select elements from the DOM.
✔️ Using getElementById() (Selects an element by ID)
let title = document.getElementById("title");
console.log(title.innerText); // Output: Hello, DOM!
✔️ Using getElementsByClassName() (Selects elements by class)
let paragraphs = document.getElementsByClassName("text");
console.log(paragraphs[0].innerText); // Output: This is a
paragraph.
✔️ Using getElementsByTagName() (Selects elements by tag name)
let allParagraphs = document.getElementsByTagName("p");
console.log(allParagraphs.length); // Output: Number of <p>
elements
✔️ Using querySelector() (Selects the first matching element)
let firstParagraph = document.querySelector(".text");
console.log(firstParagraph.innerText); // Output: This is a
paragraph.
✔️ Using querySelectorAll() (Selects all matching elements)
let allTextElements = document.querySelectorAll(".text");
console.log(allTextElements.length); // Output: Number of
elements with class "text"
B. Modifying Elements
JavaScript can modify elements in multiple ways.
✔️ Changing Text Content
document.getElementById("title").innerText = "DOM
Manipulation!";
✔️ Changing HTML Content
document.getElementById("title").innerHTML = "<span>New
Content</span>";
✔️ Changing Attributes
document.getElementById("title").setAttribute("class",
"new-class");
✔️ Changing CSS Styles
document.getElementById("title").style.color = "blue";
document.getElementById("title").style.fontSize = "24px";
C. Creating and Appending Elements
✔️ Creating a New Element
let newParagraph = document.createElement("p");
newParagraph.innerText = "This is a new paragraph.";
✔️ Appending the New Element to the Body
document.body.appendChild(newParagraph);
✔️ Appending to a Specific Element
let div = document.getElementById("container");
div.appendChild(newParagraph);
D. Removing Elements
✔️ Removing an Element Using removeChild()
let parent = document.getElementById("container");
let child = document.getElementById("title");
parent.removeChild(child);
✔️ Removing an Element Using remove()
document.getElementById("title").remove();
4. How can images, tables, and node lists be handled using JavaScript and the
DOM? Provide relevant examples.
Handling Images, Tables, and Node Lists
Using JavaScript and the DOM
1. Handling Images in the DOM
📌 JavaScript allows you to dynamically manipulate images in an HTML document.
✔️ You can change image attributes, create new images, and remove images using
JavaScript.
A. Changing an Image Source Dynamically
✔️ Use the setAttribute() method or directly modify the src property.
🔹 Example: Changing an Image on Button Click
<img id="myImage" src="image1.jpg" width="300"
height="200">
<button onclick="changeImage()">Change Image</button>
<script>
function changeImage() {
document.getElementById("myImage").src = "image2.jpg";
</script>
✔️ Clicking the button changes the image source from "image1.jpg" to
"image2.jpg".
B. Creating and Adding an Image Dynamically
✔️ Use createElement() and appendChild() to insert an image dynamically.
🔹 Example: Adding an Image to a Div
<div id="imageContainer"></div>
<script>
let img = document.createElement("img");
img.src = "newImage.jpg";
img.width = 400;
img.height = 250;
document.getElementById("imageContainer").appendChild(img);
</script>
✔️ Creates and inserts a new image into the imageContainer div.
C. Removing an Image from the DOM
✔️ Use the remove() method or removeChild().
🔹 Example: Removing an Image
<img id="myImg" src="photo.jpg">
<button onclick="removeImage()">Remove Image</button>
<script>
function removeImage() {
document.getElementById("myImg").remove();
}
</script>
✔️ Clicking the button removes the image from the document.
2. Handling Tables in the DOM
📌 JavaScript can create, modify, and delete table rows and cells dynamically.
A. Creating a Table Dynamically
✔️ Use createElement(), insertRow(), and insertCell().
🔹 Example: Creating a Table with JavaScript
<table id="myTable" border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
<button onclick="addRow()">Add Row</button>
<script>
function addRow() {
let table = document.getElementById("myTable");
let row = table.insertRow(); // Create new row
let cell1 = row.insertCell(0); // Create first cell
let cell2 = row.insertCell(1); // Create second cell
cell1.innerHTML = "John Doe";
cell2.innerHTML = "25";
</script>
✔️ Clicking the button adds a new row with data "John Doe" and "25".
B. Deleting a Table Row
✔️ Use deleteRow(index).
🔹 Example: Deleting the Last Row from a Table
<button onclick="deleteRow()">Delete Last Row</button>
<script>
function deleteRow() {
let table = document.getElementById("myTable");
let rowCount = table.rows.length;
if (rowCount > 1) { // Prevent deleting header row
table.deleteRow(rowCount - 1);
</script>
✔️ Removes the last row when the button is clicked.
3. Handling Node Lists in the DOM
📌 Node lists are collections of nodes (elements) returned by DOM methods like
querySelectorAll().
✔️ Unlike arrays, node lists do not have array methods like map() or filter().
✔️ Can be looped using forEach() or a for loop.
A. Selecting Multiple Elements Using querySelectorAll()
🔹 Example: Changing Text Color of All Paragraphs
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>
<script>
let paragraphs = document.querySelectorAll(".text");
paragraphs.forEach((p) => {
p.style.color = "blue";
});
</script>
✔️ Loops through all <p> elements and changes their color to blue.
B. Converting Node List to an Array
✔️ Use Array.from() to convert a NodeList into an array for advanced operations.
🔹 Example: Using map() on NodeList
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
<script>
let items = document.querySelectorAll("li");
let itemArray = Array.from(items);
itemArray.map(item => item.style.fontWeight = "bold");
</script>
✔️ Converts NodeList to an array and makes text bold.
C. Removing Multiple Elements Using Node List
✔️ Use forEach() to remove all selected elements.
🔹 Example: Removing All Paragraphs
<button onclick="removeAllParagraphs()">Remove All</button>
<script>
function removeAllParagraphs() {
document.querySelectorAll(".text").forEach(p =>
p.remove());
</script>
✔️ Clicking the button removes all paragraphs with the class "text".