Chapter 15: Mastering the DOM in JavaScript (Part 1)

Chapter 15: Mastering the DOM in JavaScript (Part 1)

ยท

17 min read

Table of contents

๐Ÿš€ 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

  1. Document Node:
    The topmost node representing the entire document.

  2. Element Nodes:
    Nodes representing individual HTML elements (<h1>, <p>, <div>, etc.).

  3. Attribute Nodes:
    Represent attributes within elements (class, id, src, etc.).

  4. Text Nodes:
    Represent the text content inside elements.

  5. 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

  1. 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.

  2. 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.

  3. 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.

  4. 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:

  1. Open your preferred browser (Chrome, Firefox, Edge, etc.).

  2. Press F12 or right-click on the page and select Inspect.

  3. 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

  1. Open the Developer Tools on your favorite website.

  2. Navigate to the Elements tab and observe the DOM structure.

  3. Try modifying an element's text content using the console:

     document.querySelector("h1").innerText = "Hello, DOM!";
    

๐Ÿ’ก Interesting Facts about the DOM

  1. Live Updates: Any changes made to the DOM through JavaScript are immediately reflected in the browser.

  2. Cross-platform Standard: The DOM is a W3C standard, making it consistent across all browsers.

  3. 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:

  1. Add a click event listener to document.

  2. Capture the click coordinates using the event object.

  3. Dynamically create a div element and style it as a circle.

  4. Position the circle using style.top and style.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:

  1. Adding an Event Listener: Attach a click event to the document object using addEventListener().

     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.

  2. Capturing Click Coordinates: Use the event object to access the clientX and clientY 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}`);
    
  3. Creating a Circle Dynamically: Use document.createElement() to create a new div element. Assign it a class (circle) that defines its appearance.

     const circle = document.createElement('div');
     circle.classList.add('circle');
    
  4. Styling the Circle: Set the circle's position using the style.top and style.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`;
    
  5. 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

  1. Accessing Non-existent Elements:

     let nonExistent = document.querySelector(".nonExistent");
     console.log(nonExistent); // Logs null, be cautious before accessing properties
    
  2. 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

  1. What is the difference between querySelector() and querySelectorAll()?

    • querySelector() returns the first matching element based on the given selector.

    • querySelectorAll() returns all matching elements as a NodeList.


  1. 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].


  1. 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")


  1. 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

  1. How can you efficiently update all <li> elements inside a specific <ul> using querySelectorAll()?
    Expected Answer:

     let listItems = document.querySelectorAll("ul#myList li");
     listItems.forEach(li => {
       li.textContent = "Updated Item";
     });
    

  1. 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];
    

  1. 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.


  1. What is the difference between querySelectorAll() and getElementsByClassName()? 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

  1. How can you select elements using attribute selectors with querySelector()?
    By using CSS-style attribute selectors:

     let inputField = document.querySelector('input[name="username"]');
    

  1. How do descendant combinators work with querySelector()?
    The descendant combinator (space) selects elements nested within a parent element:
document.querySelector("div p");

  1. 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()).


  1. 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

  1. 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");

  1. Why is it better to use querySelector() over older methods like getElementById() or getElementsByTagName()?
  • Cleaner and more flexible syntax.

  • Supports complex selectors.

  • Uniform API for both ID, class, and tag selectors.


  1. How do you handle a situation where multiple matching elements are required but querySelector() was mistakenly used instead of querySelectorAll()?
    Ensure that querySelectorAll() is used instead, as querySelector() will only return the first match:
document.querySelectorAll("h3").forEach(h3 => console.log(h3.innerText));

๐Ÿ” Difference Between innerHTML and innerText

Explanation

PropertyDescriptionIncludes HTML Tags?Performance Impact
innerHTMLGets or sets the HTML content inside an elementYesCan be heavier due to parsing and rendering
innerTextGets or sets only the visible text contentNoFaster as it only processes visible text

Key Differences

  1. HTML Tags:

    • innerHTML captures or modifies both text and tags inside an element.

    • innerText only captures the text visible to the user.

  2. Hidden Elements:

    • innerText ignores hidden elements (e.g., elements with display: 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

FunctionDescription
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

FeatureinnerHTMLinnerText
Includes Tagsโœ… YesโŒ No
PerformanceSlower (parses tags)Faster (only visible text)
Hidden ContentCaptures allIgnores hidden elements
Use CaseFor HTML updatesFor 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()?

FeaturequerySelector()getElementById()
Selector TypeCSS selectorElement by unique id
Return ValueFirst matching elementSingle element
Flexibilityโœ… Supports complex selectorsโŒ Limited to ID selection
PerformanceSlowerFaster

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

ย