Unit4 - Subjective Questions
INT219 • Practice Questions with Detailed Answers
Explain the structure of the Document Object Model (DOM) and describe how it represents an HTML document.
Structure of the DOM:
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can connect to the page.
- Tree Structure: The DOM is structured as a tree of objects, often referred to as the DOM Tree.
- The Root Node: The top of the tree is the
documentobject. - Element Nodes: HTML tags become element nodes (e.g.,
<body>,<div>,<p>). - Text Nodes: The text inside elements forms text nodes. Text nodes are always leaf nodes of the tree.
- Attribute Nodes: Attributes of HTML elements (like
class,id,src) are represented as attribute nodes.
Representation:
When a browser loads a web page, it creates a model of that page. For example:
- The
<html>element is the parent. <head>and<body>are children of<html>and siblings to each other.- Elements inside
<body>are its children.
This hierarchical structure allows developers to traverse the tree (move up, down, or sideways) to access and manipulate specific parts of the UI.
Differentiate between querySelector and getElementById methods in JavaScript. Provide examples for each.
1. getElementById
- Purpose: Selects a single element based on its unique
idattribute. - Return Value: Returns a reference to the first
Elementobject with the specified ID, ornullif the ID is not found. - Performance: Generally faster as it looks up a direct hash map of IDs.
- Syntax:
const element = document.getElementById("myHeader");
2. querySelector
- Purpose: Selects the first element that matches a specified CSS selector (ID, class, tag, attribute, etc.).
- Return Value: Returns the first
Elementwithin the document that matches the specified selector, ornullif no matches are found. - Flexibility: Much more flexible as it can select complex structures (e.g.,
.container > .btn.primary). - Syntax:
const element = document.querySelector("#myHeader");orconst btn = document.querySelector(".submit-btn");
Key Difference:
While getElementById is restricted strictly to IDs, querySelector accepts any valid CSS selector string, making it more powerful but slightly slower for simple ID lookups.
Describe the process of creating a new HTML element and appending it to the DOM using JavaScript.
Creating and appending elements involves a specific sequence of DOM methods. The process is as follows:
-
Create the Element:
Use thedocument.createElement(tagName)method. This creates a new element node in memory, but it is not yet part of the visible DOM.- Example:
const newDiv = document.createElement("div");
- Example:
-
Add Content or Attributes:
Before adding it to the page, you typically add content or attributes.- Adding Text:
newDiv.textContent = "Hello World"; - Adding Class:
newDiv.classList.add("box");
- Adding Text:
-
Select the Parent Element:
Identify where in the DOM tree you want to place this new element.- Example:
const parentElement = document.getElementById("container");
- Example:
-
Append the Element:
Use a method to attach the new node to the parent.appendChild(node): Adds the node as the last child of the parent.append(node or string): Modern method, allows appending multiple nodes or text strings.- Example:
parentElement.appendChild(newDiv);
Once step 4 is executed, the browser updates the UI to show the new element.
Compare innerHTML, innerText, and textContent. Which one is safer to use and why?
Comparison:
-
innerHTML:- Gets or sets the HTML markup contained within the element.
- It parses the content as HTML, meaning tags like
<strong>are rendered. - Risk: Prone to Cross-Site Scripting (XSS) attacks if used with unsanitized user input.
-
innerText:- Gets or sets the rendered text content of a node and its descendants.
- It is aware of CSS styling (e.g., it won't return text hidden with
display: none). - It triggers a reflow (layout calculation) to determine what is visible.
-
textContent:- Gets or sets the text content of a node and its descendants.
- It returns all text, including hidden text and formatting whitespace (like newlines inside the code).
- It does not parse HTML.
Safety and Usage:
textContentis generally the safest and most performant choice when you only need to set raw text. It prevents XSS because it treats input as a string, not executable HTML.innerHTMLshould only be used when you explicitly need to insert HTML elements from a trusted source.
Explain the concept of Event Propagation, specifically detailing the difference between 'Bubbling' and 'Capturing'.
Event Propagation determines the order in which event handlers are called when an event occurs on an element nested inside other elements.
1. Capturing Phase (The Trickle Down):
- The event starts from the
window, goes down to thedocument, then the<html>root, and moves down the DOM tree through ancestors until it reaches the target element. - This phase is rarely used in daily development but can be enabled by setting the third argument of
addEventListenertotrueor{ capture: true }.
2. Target Phase:
- The event reaches the actual element that triggered the event (e.g., the clicked button).
3. Bubbling Phase (The Bubble Up):
- After the target phase, the event bubbles up from the target element to its parent, then the grandparent, all the way back up to the
window. - Default Behavior: Most events bubble by default. If you click a
<button>inside a<div>, the click event fires on the button first, then the div.
Summary:
- Capturing: Outwards Inwards.
- Bubbling: Inwards Outwards.
What is 'Event Delegation'? Explain its advantages with a practical scenario.
Event Delegation is a technique involving adding a single event listener to a parent element instead of adding many listeners to individual child elements. It relies on Event Bubbling, where an event triggered on a child bubbles up to the parent.
How it works:
- Attach a listener to a common parent (e.g., a
<ul>list). - Inside the handler, check the
event.targetproperty to see which specific child element was actually clicked.
Advantages:
- Memory Efficiency: Instead of 100 listeners for 100 list items, you only need 1 listener. This reduces memory usage.
- Dynamic Content Handling: If new child elements are added dynamically (via JavaScript) after the page loads, they automatically inherit the behavior of the parent listener. You don't need to bind new listeners to new elements.
Practical Scenario:
Consider a "To-Do List" app where users can add tasks. Instead of adding a 'Delete' click listener to every new task created, you add one listener to the task container (parent). When a click occurs, you check if (e.target.className === 'delete-btn') to execute the delete logic.
How can you modify the styles of a DOM element using JavaScript? Discuss style property vs. classList.
JavaScript allows dynamic styling of elements using two primary methods:
1. The style Property (Inline Styles):
- You access the
styleobject of an element and modify CSS properties directly (using camelCase). - Example:
element.style.backgroundColor = "red"; - Pros: Good for calculating values dynamically (e.g., setting coordinates based on mouse position).
- Cons: Adds inline styles, which have high specificity and can be hard to override. It mixes logic with presentation.
2. The classList API (Class Manipulation):
- You define styles in an external CSS file and use JS to toggle classes.
- Methods:
add(),remove(),toggle(),contains(). - Example:
element.classList.add("active"); - Pros: Cleaner code (Separation of Concerns). Keeps CSS in
.cssfiles. Easier to maintain and toggle complex states. - Cons: Requires pre-defined CSS classes.
Conclusion: Use classList for state changes (active/inactive, visible/hidden) and style for dynamic values that change rapidly or are calculated (drag-and-drop coordinates, progress bar width).
Explain the significance of preventDefault() and stopPropagation() methods in event handling.
1. preventDefault()
- Purpose: It prevents the browser's default behavior associated with the event.
- Usage:
- Preventing a form from submitting and reloading the page when a submit button is clicked (
form.addEventListener('submit', ...)). - Preventing a link (
<a>) from navigating to a URL.
- Preventing a form from submitting and reloading the page when a submit button is clicked (
- Effect: It does not stop the event from bubbling; it only stops the native browser action.
2. stopPropagation()
- Purpose: It stops the event from traveling further through the DOM (stops bubbling or capturing).
- Usage:
- If you have a button inside a card, and clicking the card opens a modal, but clicking the button should only perform a button action (like 'Like'), you use
stopPropagation()on the button so the card's click event doesn't fire.
- If you have a button inside a card, and clicking the card opens a modal, but clicking the button should only perform a button action (like 'Like'), you use
- Effect: It prevents parent handlers from being notified of the event.
What are Browser Developer Tools? Describe the utility of the 'Elements' and 'Console' tabs.
Browser Developer Tools (DevTools) are a set of web authoring and debugging tools built directly into browsers (like Chrome, Firefox).
1. Elements Tab:
- DOM Inspection: View the live DOM structure of the page. You can see the HTML as the browser renders it (including dynamic JS changes).
- Style Debugging: View and edit CSS rules applied to any selected element. You can toggle styles, check the Box Model (margins, padding), and see computed styles.
- Live Editing: You can double-click tags or attributes to modify them instantly to test changes without reloading.
2. Console Tab:
- Logging: Displays messages logged from JavaScript using
console.log(),console.warn(), orconsole.error(). - Error Tracking: Shows JavaScript syntax errors, runtime exceptions, and network 404 errors.
- Interactive Shell: Allows developers to write and execute JavaScript code directly in the context of the current page (e.g., selecting elements, testing functions).
Explain how to debug JavaScript code using breakpoints in the 'Sources' (or 'Debugger') panel of browser developer tools.
Debugging with breakpoints is more efficient than using console.log.
Process:
- Open DevTools: Press F12 or right-click and Inspect, then navigate to the Sources (Chrome) or Debugger (Firefox) tab.
- Locate File: In the file navigator, find and open the JavaScript file you wish to debug.
- Set Breakpoint: Click on the line number in the gutter (left of the code). A blue marker usually appears. The code execution will now pause automatically whenever it reaches this line.
- Trigger Code: Perform the action on the webpage (e.g., click a button) that runs that code.
- Debug Controls: Once paused, you can use:
- Resume: Continue until the next breakpoint.
- Step Over: Execute the current line and move to the next.
- Step Into: If the line is a function call, go inside that function.
- Step Out: Finish the current function and return to the caller.
- Inspect State: While paused, hover over variables to see their current values or check the 'Scope' pane to view all local and global variables.
What is DOM Traversal? List and explain three properties used to traverse the DOM tree relative to a selected node.
DOM Traversal is the act of selecting an element and then moving (navigating) to another element based on their relationship in the DOM tree (parent, child, or sibling).
Key Properties:
-
parentNode(orparentElement):- Selects the immediate parent of the current node.
- Usage: Moving up the tree. If you have a
<td>and want to style the row<tr>containing it.
-
children(orchildNodes):childrenreturns a live HTMLCollection of child elements (ignoring text nodes).childNodesreturns a NodeList including text nodes and comments.- Usage: Moving down the tree to access items inside a container.
-
nextElementSibling/previousElementSibling:- Navigates sideways to the adjacent node on the same tree level.
- Usage: If you have a list of items and need to access the item immediately following the current one.
- Note: Using
nextSiblingmight return a text node (whitespace), sonextElementSiblingis preferred for HTML tags.
What is Module Bundling? Why is it essential in modern front-end development?
Module Bundling is the process of taking multiple JavaScript files (modules) and their dependencies and combining them into a single file (or a few files), often called a "bundle."
Why it is essential:
- Performance (HTTP Requests): Browsers historically had limits on how many parallel files they could download. Loading 50 separate JS files is slower than loading 1 large bundle due to network overhead. (Though HTTP/2 alleviates this, bundling is still standard).
- Dependency Management: Bundlers (like Webpack, Vite, Parcel) create a dependency graph. They ensure that modules are loaded in the correct order, resolving imports and exports automatically.
- Code Transformation: Bundlers integrate with loaders/plugins to facilitate:
- Transpilation: Converting modern ES6+ code to older ES5 (via Babel) for browser compatibility.
- Preprocessing: Converting SASS/SCSS to CSS or TypeScript to JavaScript.
- Optimization: Bundlers perform Minification (removing whitespace/comments) and Tree Shaking (removing unused code) to reduce file size.
Explain the concepts of 'Tree Shaking' and 'Minification' in the context of build tools.
1. Tree Shaking:
- Definition: A form of dead code elimination used by bundlers like Webpack or Rollup.
- How it works: It relies on the static structure of ES6 modules (
importandexport). The bundler analyzes the dependency graph to determine which exports are actually used in the application. Any code that is exported but never imported/used is "shaken off" (removed) from the final bundle. - Benefit: Significantly reduces the final bundle size by excluding unused library functions.
2. Minification:
- Definition: The process of compressing code files without changing their functionality.
- How it works:
- Removes unnecessary characters (whitespace, newlines, comments).
- Shortens variable and function names (e.g., renaming
function calculateTotal()tofunction a()).
- Benefit: Reduces file size, leading to faster download times and parsing for the browser.
What is Code Linting? How does ESLint help developers maintain code quality?
Code Linting is the process of running a program (a linter) that analyzes code for potential errors, stylistic inconsistencies, and suspicious constructs.
How ESLint helps:
- Detects Syntax Errors: It catches typos and syntax errors (like missing brackets) before the code is even run.
- Enforces Best Practices: It flags anti-patterns, such as using variables before they are defined, using
==instead of===, or unreachable code. - Ensures Consistency: In a team environment, ESLint ensures everyone follows the same coding rules (e.g., semicolon usage, variable naming conventions).
- Customizability: ESLint is highly configurable. Developers can extend standard rule sets (like Airbnb or Google style guides) or define their own rules in an
.eslintrcfile. - Integration: It integrates with IDEs (VS Code) to underline errors in red in real-time as you type.
Distinguish between Code Linting (e.g., ESLint) and Code Formatting (e.g., Prettier).
Code Linting (e.g., ESLint):
- Focus: Code quality and logic.
- Primary Goal: To catch bugs, syntax errors, and bad coding practices.
- Examples of what it fixes: Unused variables, infinite loops, usage of
varinstead oflet/const, missing equality checks. - Modification: It warns the developer, and while it can fix some things, it primarily acts as a quality gate.
Code Formatting (e.g., Prettier):
- Focus: Code style and visual presentation.
- Primary Goal: To make code readable and consistent regardless of who wrote it.
- Examples of what it fixes: Indentation size (2 spaces vs 4), single vs double quotes, line wrapping length, spacing inside brackets.
- Modification: It rewrites the code layout entirely to match the configured style rules, usually on file save.
Summary: Linting checks what your code does; Formatting checks how your code looks.
Explain the use of dataset in JavaScript to handle custom data attributes in HTML.
HTML5 introduced custom data attributes, allowing developers to store extra information on standard HTML elements without using non-standard attributes. These attributes must start with data-.
HTML Example:
<div id="user" data-user-id="123" data-role="admin">John Doe</div>
Using dataset in JavaScript:
The dataset property on a DOM element provides a read/write interface to these attributes via a map of strings (DOMStringMap).
-
Accessing Data:
Hyphenated attributes in HTML turn into camelCase properties in JS.const userDiv = document.getElementById('user');console.log(userDiv.dataset.userId);// Outputs: "123"console.log(userDiv.dataset.role);// Outputs: "admin"
-
Modifying Data:
You can assign values directly.userDiv.dataset.role = "editor";// Updates the HTML attribute todata-role="editor"
-
Use Cases: Storing IDs for API calls, configuration states for UI components, or parameters for JavaScript logic that are linked to specific DOM elements.
Discuss the performance implications of frequent DOM manipulation. What is 'Reflow' and 'Repaint'?
The DOM is the bottleneck in frontend performance. JavaScript is fast, but touching the DOM is slow because it requires the browser to recalculate layout and render pixels.
1. Reflow (Layout):
- Definition: The process where the browser calculates the position and geometry of elements in the document.
- Triggers: Adding/removing elements, resizing the window, changing font sizes, or changing layout properties (width, height, margin).
- Impact: Reflow is computationally expensive. A reflow of an element often causes a reflow of its parents and children.
2. Repaint (Draw):
- Definition: The process where the browser paints the pixels to the screen after the layout is calculated.
- Triggers: Changing visibility, background color, or outline (properties that don't affect layout geometry).
- Impact: Expensive, but generally faster than Reflow.
Performance Implications:
Frequent DOM updates cause "Layout Thrashing." To optimize:
- Batch DOM changes (read layout properties first, then write changes).
- Use
DocumentFragmentto build a subtree off-screen and append it once. - Use CSS classes (
classList) instead of setting individual style properties.
How does a 'DocumentFragment' improve DOM manipulation efficiency? Provide an example.
Concept:
A DocumentFragment is a lightweight, off-screen DOM object. It acts as a temporary container. When you append a fragment to the DOM, only the content of the fragment is inserted, not the fragment node itself.
Efficiency:
If you need to add 100 list items (<li>) to a <ul>:
- Without Fragment: Appending each
<li>directly to the<ul>triggers a Reflow/Repaint 100 times. - With Fragment: You append the 100
<li>s to the Fragment (which is in memory, not on screen). Then, you append the Fragment to the<ul>. This triggers only 1 Reflow/Repaint.
Example:
javascript
const list = document.getElementById('myList');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 50; i++) {
const li = document.createElement('li');
li.textContent = Item ${i};
fragment.appendChild(li); // No reflow here
}
list.appendChild(fragment); // Only 1 reflow here
Describe the modern development workflow involving 'transpiling'. Why is Babel commonly used?
Transpiling (Transformation + Compiling) is the process of taking source code written in one language (or version) and transforming it into another language (or version) that has a similar level of abstraction.
Role of Babel:
JavaScript evolves rapidly (ES6, ES7, ESNext), introducing features like Arrow Functions () => {}, Classes, and Async/Await. However, older browsers (like Internet Explorer or older versions of Safari) do not understand this new syntax.
Why Babel is used:
- Backward Compatibility: Babel converts modern ES6+ JavaScript into ES5 JavaScript, which is universally supported by almost all browsers.
- Polyfilling: Features like
PromiseorArray.includesmight not exist in old browsers. Babel (often alongside core-js) adds code to simulate these missing features. - JSX Support: In React development, Babel transforms JSX (HTML-like syntax in JS) into standard
React.createElement()calls.
This allows developers to write clean, modern code without worrying about breaking the site for users on older devices.
Write a short note on how to programmatically remove an element from the DOM using old vs. modern methods.
Removing elements can be done using the child-parent relationship or directly on the element itself.
1. The Old Method (removeChild):
Traditionally, you could not remove a node directly. You had to select the parent, and then tell the parent to remove the specific child.
- Syntax:
parentNode.removeChild(childNode); - Example:
javascript
const element = document.getElementById("target");
element.parentNode.removeChild(element);
2. The Modern Method (remove):
In modern browsers (ES6+), elements have a direct remove() method. This is much cleaner and intuitive.
- Syntax:
element.remove(); - Example:
javascript
const element = document.getElementById("target");
element.remove();
Both methods remove the node from the DOM tree, but the node object still exists in JavaScript memory until variables referencing it are cleared.