Table of contents
- ๐ Introduction to the DOM
- ๐ฏ Assignment 1: Create a Circle on Click (Pure JavaScript)
- ๐ Detailed Steps:
- ๐ง Improved Solution with Click Animation:
- ๐ Enhancements and Improvements:
- ๐ Final Enhanced Version:
- ๐ฏ Key Learning Points:
- ๐งโ๐ป DOM Selectors
- 1. querySelector() vs querySelectorAll()
- Practical Example: Selecting Elements Dynamically
- Selecting Elements with Complex Selectors
- Converting NodeList to an Array
- Advanced Use Case: Filtering Elements
- Common Mistakes to Avoid
- 1๏ธโฃ Basic Usage of querySelector() and querySelectorAll()
- 2๏ธโฃ Converting NodeList to an Array
- 3๏ธโฃ Filtering Elements in a Dynamic List
- 4๏ธโฃ Selecting by Complex Selectors (Class, ID, and Attributes)
- 5๏ธโฃ Real-world Example: Highlighting Elements on Mouse Hover
- Basic Questions
- Intermediate Questions
- Advanced Questions
- Tricky/Edge Case Questions
- ๐ Difference Between innerHTML and innerText
- ๐ Interactive Alerts and Prompts
- ๐ค Interview Questions
๐ Learn to Harness the Power of the Document Object Model (DOM)
๐ Introduction to the DOM
The Document Object Model (DOM) is a crucial concept in web development. It serves as a bridge between web content (HTML or XML documents) and the programming languages (like JavaScript) that control them. When a webpage is loaded, the browser creates a live representation of the content, known as the DOM. This allows developers to interact programmatically with the page, altering its content, styles, and behavior without requiring a full page reload.
๐ ๏ธ How the DOM Works
The DOM represents the structure of a webpage as a tree of objects where:
Each HTML element becomes a node in the tree.
Attributes and text within elements are also represented as nodes.
Relationships between elements, such as parent-child and sibling nodes, are maintained.
Imagine a simple webpage:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a sample webpage.</p>
</body>
</html>
The DOM tree for this page looks like this:
Document
โโโ html
โ โโโ head
โ โ โโโ title
โ โโโ body
โ โโโ h1
โ โโโ p
๐งฉ Key Components of the DOM
Document Node:
The topmost node representing the entire document.Element Nodes:
Nodes representing individual HTML elements (<h1>
,<p>
,<div>
, etc.).Attribute Nodes:
Represent attributes within elements (class
,id
,src
, etc.).Text Nodes:
Represent the text content inside elements.Parent, Child, and Sibling Relationships:
Nodes maintain hierarchical relationships:Parent Node: A node containing child nodes.
Child Node: A node directly contained within another node.
Sibling Nodes: Nodes that share the same parent.
๐ Why DOM Matters
Interactive Pages:
The DOM allows developers to respond to user actions, such as clicks and keyboard events. For example, clicking a button can trigger a JavaScript function to display a message.Content Manipulation:
Developers can dynamically add, remove, or update elements on a page. For instance, a shopping cart page can update the total cost without reloading.Real-time Updates:
The DOM is essential for building modern web applications that need real-time updates. Applications like chat systems or dashboards often rely on DOM manipulation to display new data dynamically.Seamless User Experience:
By enabling changes without a full page reload, the DOM contributes to a smoother and faster user experience.
๐ป Exploring the DOM with Console
You can inspect and explore the DOM using the browser's Developer Tools.
Steps to Open the Developer Tools:
Open your preferred browser (Chrome, Firefox, Edge, etc.).
Press F12 or right-click on the page and select Inspect.
Navigate to the Console tab to execute and view JavaScript code.
Example Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Explore DOM</title>
</head>
<body>
<h1>Welcome to the DOM!</h1>
<p>Explore the Document Object Model.</p>
<script>
console.log(window.document); // Complete DOM structure
console.log(document.documentElement); // Root HTML element
console.log(document.head); // Head section
console.log(document.body); // Body section
</script>
</body>
</html>
What This Code Demonstrates:
console.log(window.document);
: Logs the complete DOM tree.console.log(document.documentElement);
: Logs the root<html>
element.console.log(document.head);
: Logs the<head>
section.console.log(document.body);
: Logs the<body>
section.
๐ Tip: Inspecting these console logs helps visualize the hierarchy and structure of the DOM.
๐ Quick Assignment: DOM Tree Analysis
Open the Developer Tools on your favorite website.
Navigate to the Elements tab and observe the DOM structure.
Try modifying an element's text content using the console:
document.querySelector("h1").innerText = "Hello, DOM!";
๐ก Interesting Facts about the DOM
Live Updates: Any changes made to the DOM through JavaScript are immediately reflected in the browser.
Cross-platform Standard: The DOM is a W3C standard, making it consistent across all browsers.
Event Handling: The DOM allows developers to attach events to elements, such as mouse clicks and key presses.
๐ฏ Assignment 1: Create a Circle on Click (Pure JavaScript)
Objective: When the user clicks anywhere on the webpage, a circle should appear at the click location.
Steps to Solve:
Add a click event listener to
document
.Capture the click coordinates using the event object.
Dynamically create a
div
element and style it as a circle.Position the circle using
style.top
andstyle.left
.
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Circle on Click</title>
<style>
body {
height: 100vh;
background-color: #f0f8ff;
cursor: crosshair;
}
.circle {
width: 30px;
height: 30px;
background-color: blue;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<script>
document.addEventListener('click', (event) => {
const circle = document.createElement('div');
circle.classList.add('circle');
circle.style.top = `${event.clientY - 15}px`;
circle.style.left = `${event.clientX - 15}px`;
document.body.appendChild(circle);
});
</script>
</body>
</html>
This assignment focuses on dynamically generating a circle at the location of the user's click anywhere on the webpage.
๐ Detailed Steps:
Adding an Event Listener: Attach a click event to the
document
object usingaddEventListener()
.document.addEventListener('click', (event) => { // Code to handle the click event goes here });
This ensures that every click on the document triggers the specified callback function.
Capturing Click Coordinates: Use the
event
object to access theclientX
andclientY
properties, which give the click's x and y coordinates relative to the viewport.const x = event.clientX; const y = event.clientY; console.log(`X: ${x}, Y: ${y}`);
Creating a Circle Dynamically: Use
document.createElement()
to create a newdiv
element. Assign it a class (circle
) that defines its appearance.const circle = document.createElement('div'); circle.classList.add('circle');
Styling the Circle: Set the circle's position using the
style.top
andstyle.left
properties. Adjust the coordinates by subtracting half the circle's diameter to center it around the click point.circle.style.top = `${event.clientY - 15}px`; circle.style.left = `${event.clientX - 15}px`;
Appending the Circle to the Document: Use
document.body.appendChild()
to add the circle to the webpage.document.body.appendChild(circle);
๐ง Improved Solution with Click Animation:
Let's enhance the circle effect by adding an animation that fades out the circle after a few seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Circle on Click</title>
<style>
body {
height: 100vh;
background-color: #f0f8ff;
cursor: crosshair;
}
.circle {
width: 30px;
height: 30px;
background-color: blue;
border-radius: 50%;
position: absolute;
animation: fade-out 2s forwards;
}
@keyframes fade-out {
to {
opacity: 0;
transform: scale(2);
}
}
</style>
</head>
<body>
<script>
document.addEventListener('click', (event) => {
const circle = document.createElement('div');
circle.classList.add('circle');
circle.style.top = `${event.clientY - 15}px`;
circle.style.left = `${event.clientX - 15}px`;
document.body.appendChild(circle);
// Remove circle after animation ends
setTimeout(() => circle.remove(), 2000);
});
</script>
</body>
</html>
๐ Enhancements and Improvements:
โ Improved Position Calculation:
To ensure the circle is perfectly centered at the click location:
circle.style.top = `${event.clientY - circle.offsetHeight / 2}px`;
circle.style.left = `${event.clientX - circle.offsetWidth / 2}px`;
โ Random Color for Each Circle:
Make the circles appear in random colors:
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
circle.style.backgroundColor = getRandomColor();
โ Dynamic Circle Size:
Randomize the size of each circle:
const size = Math.floor(Math.random() * 50) + 10; // Size between 10px and 60px
circle.style.width = `${size}px`;
circle.style.height = `${size}px`;
๐ Final Enhanced Version:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced Circle Click Effect</title>
<style>
body {
height: 100vh;
background-color: #f0f8ff;
cursor: crosshair;
overflow: hidden;
}
.circle {
position: absolute;
border-radius: 50%;
animation: fade-out 1.5s forwards;
}
@keyframes fade-out {
to {
opacity: 0;
transform: scale(2);
}
}
</style>
</head>
<body>
<script>
document.addEventListener('click', (event) => {
const circle = document.createElement('div');
const size = Math.floor(Math.random() * 50) + 10;
const color = getRandomColor();
circle.classList.add('circle');
circle.style.width = `${size}px`;
circle.style.height = `${size}px`;
circle.style.backgroundColor = color;
circle.style.top = `${event.clientY - size / 2}px`;
circle.style.left = `${event.clientX - size / 2}px`;
document.body.appendChild(circle);
setTimeout(() => circle.remove(), 1500);
});
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>
๐ฏ Key Learning Points:
Event Handling: How to attach events using
addEventListener()
.Dynamic Element Creation: Using
document.createElement()
to add new elements to the DOM.Coordinate Calculation: Proper positioning using event coordinates and element sizes.
Animations: CSS animations and how to trigger them dynamically.
Randomization: Adding randomness for dynamic user experiences.
๐งโ๐ป DOM Selectors
1. querySelector() vs querySelectorAll()
querySelector()
Selects the first matching element that matches the specified CSS selector.
Useful when you know there's only one instance or when selecting the first element is sufficient.
querySelectorAll()
Selects all matching elements that match the given CSS selector.
Returns a NodeList, which is similar to an array but does not have all array methods (like
.map()
).
Practical Example: Selecting Elements Dynamically
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Selectors Example</title>
</head>
<body>
<h3>Header 1</h3>
<h3>Header 2</h3>
<h3>Header 3</h3>
<p>This is a paragraph</p>
<button id="changeText">Change Header Texts</button>
<script>
// Select the first <h3> element
let firstH3 = document.querySelector("h3");
console.log(firstH3.innerText); // Logs "Header 1"
// Select all <h3> elements and log their inner text
let allH3s = document.querySelectorAll("h3");
allH3s.forEach(h3 => console.log(h3.innerText)); // Logs all headers
// Event to change all headers on button click
document.getElementById("changeText").addEventListener("click", () => {
allH3s.forEach((h3, index) => {
h3.innerText = `Updated Header ${index + 1}`;
});
});
</script>
</body>
</html>
Expected Output:
Before clicking the button: Console logs "Header 1", "Header 2", "Header 3".
After clicking the button: All headers update to "Updated Header 1", "Updated Header 2", and so on.
Selecting Elements with Complex Selectors
1. ID Selector
let button = document.querySelector("#changeText");
console.log(button); // Logs the button element
2. Class Selector
<p class="info">Info 1</p>
<p class="info">Info 2</p>
<script>
let infoParagraphs = document.querySelectorAll(".info");
console.log(infoParagraphs.length); // Logs 2
</script>
3. Attribute Selector
<input type="text" name="username" value="Rohit">
<script>
let inputField = document.querySelector('input[name="username"]');
console.log(inputField.value); // Logs "Rohit"
</script>
4. Descendant Combinator Selector
let nestedParagraph = document.querySelector("div p");
Converting NodeList to an Array
Why Convert?
A NodeList
does not have all the methods that arrays offer, such as .map()
or .filter()
. Converting it to an array provides access to these methods.
Method 1: Using Array.from()
let allH3 = document.querySelectorAll("h3");
let h3Array = Array.from(allH3);
h3Array.map(h3 => console.log(h3.innerText)); // Logs updated header texts
Method 2: Using Spread Operator [...NodeList]
let h3Array = [...allH3];
h3Array.map(h3 => console.log(h3.innerText));
Advanced Use Case: Filtering Elements
Imagine you want to find only the headers that contain the word "Updated."
let filteredHeaders = h3Array.filter(h3 => h3.innerText.includes("Updated"));
console.log(filteredHeaders);
Common Mistakes to Avoid
Accessing Non-existent Elements:
let nonExistent = document.querySelector(".nonExistent"); console.log(nonExistent); // Logs null, be cautious before accessing properties
NodeList vs HTMLCollection:
querySelectorAll()
returns a NodeList.Methods like
getElementsByTagName()
return an HTMLCollection, which is live (automatically updates if elements are added/removed).
1๏ธโฃ Basic Usage of querySelector()
and querySelectorAll()
This example shows how to select and modify elements using the two methods.
File: basic-selectors.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Basic Selectors</title>
</head>
<body>
<h1>Main Header</h1>
<h3>Header 1</h3>
<h3>Header 2</h3>
<button id="changeHeaders">Change Header Texts</button>
<script>
// Selecting single element
const firstH3 = document.querySelector("h3");
console.log("First H3: " + firstH3.innerText);
// Selecting all matching elements
const allH3s = document.querySelectorAll("h3");
allH3s.forEach(h3 => console.log(h3.innerText));
// Changing all header texts
document.getElementById("changeHeaders").addEventListener("click", () => {
allH3s.forEach((h3, index) => {
h3.innerText = `Updated Header ${index + 1}`;
});
});
</script>
</body>
</html>
2๏ธโฃ Converting NodeList to an Array
Demonstrates both Array.from()
and the spread operator for converting NodeList.
File: nodelist-to-array.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>NodeList Conversion</title>
</head>
<body>
<h3>Header A</h3>
<h3>Header B</h3>
<h3>Header C</h3>
<script>
const headersNodeList = document.querySelectorAll("h3");
// Convert NodeList using Array.from()
const headersArray1 = Array.from(headersNodeList);
headersArray1.map(h3 => console.log("Array.from: " + h3.innerText));
// Convert NodeList using Spread Operator
const headersArray2 = [...headersNodeList];
headersArray2.map(h3 => console.log("Spread Operator: " + h3.innerText));
</script>
</body>
</html>
3๏ธโฃ Filtering Elements in a Dynamic List
A practical example where only headers containing the word "Updated" are filtered.
File: filtering-elements.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Filtering Elements</title>
</head>
<body>
<h3>Updated Header 1</h3>
<h3>Regular Header 2</h3>
<h3>Updated Header 3</h3>
<script>
const allH3s = document.querySelectorAll("h3");
const updatedHeaders = [...allH3s].filter(h3 => h3.innerText.includes("Updated"));
console.log("Filtered Headers:");
updatedHeaders.forEach(h3 => console.log(h3.innerText));
</script>
</body>
</html>
4๏ธโฃ Selecting by Complex Selectors (Class, ID, and Attributes)
Demonstrates how to use various complex selectors.
File: complex-selectors.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Complex Selectors</title>
</head>
<body>
<p id="uniqueParagraph">This is an ID-based paragraph</p>
<p class="common">Class-based paragraph 1</p>
<p class="common">Class-based paragraph 2</p>
<input type="text" name="username" value="Rohit">
<script>
// ID Selector
let uniqueParagraph = document.querySelector("#uniqueParagraph");
console.log(uniqueParagraph.innerText);
// Class Selector
let classParagraphs = document.querySelectorAll(".common");
classParagraphs.forEach(p => console.log(p.innerText));
// Attribute Selector
let inputField = document.querySelector('input[name="username"]');
console.log("Input value: " + inputField.value);
</script>
</body>
</html>
5๏ธโฃ Real-world Example: Highlighting Elements on Mouse Hover
Shows how to dynamically apply styles using querySelectorAll()
.
File: hover-highlight.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hover Highlight</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<h3>Hover over this header</h3>
<h3>Hover over this header too</h3>
<script>
const headers = document.querySelectorAll("h3");
headers.forEach(header => {
header.addEventListener("mouseover", () => {
header.classList.add("highlight");
});
header.addEventListener("mouseout", () => {
header.classList.remove("highlight");
});
});
</script>
</body>
</html>
Basic Questions
What is the difference between
querySelector()
andquerySelectorAll()
?querySelector()
returns the first matching element based on the given selector.querySelectorAll()
returns all matching elements as a NodeList.
What is a NodeList? How is it different from an Array?
A NodeList is a collection of DOM nodes returned by methods like
querySelectorAll()
.Unlike arrays, NodeLists do not have built-in methods such as
.map()
,.filter()
, or.reduce()
.NodeLists can be converted to arrays using
Array.from()
or the spread operator[...NodeList]
.
How do you select elements by class name, ID, or tag using
querySelector()
? Expected Answer:By class:
document.querySelector(".myClass")
By ID:
document.querySelector("#myID")
By tag:
document.querySelector("h1")
Can
querySelector()
select multiple classes at once? If yes, how?
Expected Answer:
Yes, by chaining the classes as in CSS:document.querySelector(".class1.class2");
Intermediate Questions
How can you efficiently update all
<li>
elements inside a specific<ul>
usingquerySelectorAll()
?
Expected Answer:let listItems = document.querySelectorAll("ul#myList li"); listItems.forEach(li => { li.textContent = "Updated Item"; });
Why is it important to convert a
NodeList
to an Array? How do you do it?Converting a
NodeList
to an array allows the use of array methods like.map()
or.filter()
.
Conversion methods:let arrayFromNodeList = Array.from(nodeList); let spreadArray = [...nodeList];
What happens if no element matches the
querySelector()
selector?It returns
null
.You should always check for
null
before accessing properties to avoid runtime errors.
What is the difference between
querySelectorAll()
andgetElementsByClassName()
? Expected Answer:querySelectorAll()
returns a static NodeList (does not update if elements are added/removed dynamically).getElementsByClassName()
returns a live HTMLCollection that updates automatically.
Advanced Questions
How can you select elements using attribute selectors with
querySelector()
?
By using CSS-style attribute selectors:let inputField = document.querySelector('input[name="username"]');
- How do descendant combinators work with
querySelector()
?
The descendant combinator (space
) selects elements nested within a parent element:
document.querySelector("div p");
- What is the difference between a live and a static collection of elements?
Live collection: Automatically reflects changes in the DOM (e.g.,
getElementsByClassName()
).Static collection: Remains unchanged after initial retrieval (e.g.,
querySelectorAll()
).
- How would you filter only
<h3>
elements that contain specific text?
let h3Elements = document.querySelectorAll("h3");
let filtered = Array.from(h3Elements).filter(h3 => h3.innerText.includes("Specific Text"));
console.log(filtered);
Tricky/Edge Case Questions
What happens if
querySelector()
is called on an element that has children?It searches only within that element's subtree:
let parentDiv = document.querySelector("#parent");
let childElement = parentDiv.querySelector(".child");
- Why is it better to use
querySelector()
over older methods likegetElementById()
orgetElementsByTagName()
?
Cleaner and more flexible syntax.
Supports complex selectors.
Uniform API for both ID, class, and tag selectors.
- How do you handle a situation where multiple matching elements are required but
querySelector()
was mistakenly used instead ofquerySelectorAll()
?
Ensure thatquerySelectorAll()
is used instead, asquerySelector()
will only return the first match:
document.querySelectorAll("h3").forEach(h3 => console.log(h3.innerText));
๐ Difference Between innerHTML
and innerText
Explanation
Property | Description | Includes HTML Tags? | Performance Impact |
innerHTML | Gets or sets the HTML content inside an element | Yes | Can be heavier due to parsing and rendering |
innerText | Gets or sets only the visible text content | No | Faster as it only processes visible text |
Key Differences
HTML Tags:
innerHTML
captures or modifies both text and tags inside an element.innerText
only captures the text visible to the user.
Hidden Elements:
innerText
ignores hidden elements (e.g., elements withdisplay: none
).innerHTML
captures all content regardless of visibility.
Examples
1๏ธโฃ HTML Content Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>innerHTML vs innerText</title>
</head>
<body>
<div id="content">
<h1>Title</h1>
<p>This is a paragraph.</p>
</div>
<script>
let contentDiv = document.getElementById("content");
console.log("Using innerHTML:");
console.log(contentDiv.innerHTML); // Logs "<h1>Title</h1><p>This is a paragraph.</p>"
console.log("Using innerText:");
console.log(contentDiv.innerText); // Logs "Title\nThis is a paragraph."
</script>
</body>
</html>
2๏ธโฃ Hidden Element Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>innerText vs innerHTML</title>
</head>
<body>
<div id="container">
<p>Visible text</p>
<p style="display: none;">Hidden text</p>
</div>
<script>
let containerDiv = document.getElementById("container");
console.log(containerDiv.innerText); // Logs only "Visible text"
console.log(containerDiv.innerHTML); // Logs "<p>Visible text</p><p style="display: none;">Hidden text</p>"
</script>
</body>
</html>
๐ Interactive Alerts and Prompts
Common Dialog Methods
Function | Description |
alert() | Displays a simple message in an alert box. |
confirm() | Asks the user for confirmation (OK/Cancel). |
prompt() | Captures user input. |
Examples
1๏ธโฃ Simple Alert
alert("Hello, Rohit!"); // Displays an alert with a simple message
2๏ธโฃ Delayed Alert
setTimeout(() => {
alert("This is a delayed alert!");
}, 2000); // Delays the alert for 2 seconds
3๏ธโฃ Confirmation Dialog
let userConfirmation = confirm("Are you sure?");
if (userConfirmation) {
console.log("User pressed OK.");
} else {
console.log("User pressed Cancel.");
}
4๏ธโฃ User Input Prompt
let userName = prompt("What is your name?");
if (userName) {
console.log(`Hello, ${userName}!`);
} else {
console.log("No name entered.");
}
Complete HTML File :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Alerts and Prompts</title>
</head>
<body>
<h1>Interactive Alerts and Prompts Examples</h1>
<button onclick="showAlert()">Simple Alert</button>
<button onclick="showDelayedAlert()">Delayed Alert (2 Seconds)</button>
<button onclick="getUserConfirmation()">Confirmation Dialog</button>
<button onclick="getUserInput()">Prompt for Name</button>
<script>
// Simple alert
function showAlert() {
alert("Hello, Rohit!");
}
// Delayed alert after 2 seconds
function showDelayedAlert() {
setTimeout(() => {
alert("This is a delayed alert!");
}, 2000);
}
// Confirmation dialog example
function getUserConfirmation() {
let userConfirmation = confirm("Are you sure?");
if (userConfirmation) {
console.log("User pressed OK.");
alert("You pressed OK!");
} else {
console.log("User pressed Cancel.");
alert("You pressed Cancel!");
}
}
// Prompt for user input
function getUserInput() {
let userName = prompt("What is your name?");
if (userName) {
console.log(`Hello, ${userName}!`);
alert(`Hello, ${userName}!`);
} else {
alert("No name entered.");
}
}
</script>
</body>
</html>
๐ค Interview Questions
1๏ธโฃ What is the DOM, and how does it work?
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 nodes.How it Works:
The DOM allows developers to traverse, modify, and update content dynamically using JavaScript.
Changes in the DOM are immediately reflected in the browser.
2๏ธโฃ Difference Between innerHTML
and innerText
Feature | innerHTML | innerText |
Includes Tags | โ Yes | โ No |
Performance | Slower (parses tags) | Faster (only visible text) |
Hidden Content | Captures all | Ignores hidden elements |
Use Case | For HTML updates | For plain text retrieval |
3๏ธโฃ How do you convert a NodeList to an array?
Using
Array.from()
let allH3 = document.querySelectorAll("h3"); let h3Array = Array.from(allH3); h3Array.map(h3 => console.log(h3.innerText));
Using the Spread Operator
let h3Array = [...allH3]; h3Array.map(h3 => console.log(h3.innerText));
4๏ธโฃ What is the difference between querySelector()
and getElementById()
?
Feature | querySelector() | getElementById() |
Selector Type | CSS selector | Element by unique id |
Return Value | First matching element | Single element |
Flexibility | โ Supports complex selectors | โ Limited to ID selection |
Performance | Slower | Faster |
Other Series:
Connect with Me
Stay updated with my latest posts and projects by following me on social media:
LinkedIn: Connect with me for professional updates and insights.
GitHub: Explore my repository and contributions to various projects.
LeetCode: Check out my coding practice and challenges.
Your feedback and engagement are invaluable. Feel free to reach out with questions, comments, or suggestions. Happy coding!
Rohit Gawande
Full Stack Java Developer | Blogger | Coding Enthusiast