Chapter 11 Intermediate 58 Questions

Practice Questions — DOM Selection and Manipulation

← Back to Notes
10 Easy
12 Medium
8 Hard

Topic-Specific Questions

Question 1
Easy
Given this HTML and JS, what is logged to the console?
<h1 id="title">Hello World</h1>

<script>
const el = document.getElementById("title");
console.log(el.textContent);
</script>
textContent returns the text inside the element.
Hello World
Question 2
Easy
What does this code log?
<p id="msg">Good <strong>Morning</strong></p>

<script>
const p = document.getElementById("msg");
console.log(p.textContent);
console.log(p.innerHTML);
</script>
textContent strips HTML tags. innerHTML preserves them.
Good Morning
Good <strong>Morning</strong>
Question 3
Easy
What is logged?
<ul>
  <li class="item">Apple</li>
  <li class="item">Banana</li>
  <li class="item">Cherry</li>
</ul>

<script>
const items = document.querySelectorAll(".item");
console.log(items.length);
</script>
querySelectorAll returns all matching elements.
3
Question 4
Easy
What does this code log?
<input type="text" id="username" value="Aarav">

<script>
const input = document.getElementById("username");
console.log(input.value);
input.value = "Priya";
console.log(input.value);
</script>
The .value property reads and sets the current value of an input.
Aarav
Priya
Question 5
Easy
What is logged?
<div id="box" class="card active">Hello</div>

<script>
const box = document.getElementById("box");
console.log(box.classList.contains("active"));
console.log(box.classList.contains("hidden"));
</script>
classList.contains() checks if an element has a specific class.
true
false
Question 6
Easy
What is logged after this code runs?
<p id="text">Original</p>

<script>
const p = document.getElementById("text");
p.textContent = "Updated";
console.log(p.textContent);
</script>
Setting textContent replaces the element's text.
Updated
Question 7
Medium
What is logged?
<div id="box" class="card">Hello</div>

<script>
const box = document.getElementById("box");
const result1 = box.classList.toggle("active");
console.log(result1);
console.log(box.className);

const result2 = box.classList.toggle("active");
console.log(result2);
console.log(box.className);
</script>
toggle() returns true if the class was added, false if removed. className returns all classes as a string.
true
card active
false
card
Question 8
Medium
What is logged?
<img id="pic" src="cat.jpg" alt="A cat">

<script>
const img = document.getElementById("pic");
console.log(img.getAttribute("alt"));
img.setAttribute("alt", "A dog");
console.log(img.getAttribute("alt"));
console.log(img.hasAttribute("title"));
</script>
getAttribute reads, setAttribute writes, hasAttribute checks existence.
A cat
A dog
false
Question 9
Medium
What does the h1 display after this code runs?
<h1 id="heading">Welcome</h1>

<script>
const h1 = document.getElementById("heading");
h1.innerHTML = "Hello <span style='color:red'>World</span>";
</script>
innerHTML parses and renders HTML tags.
The h1 displays "Hello World" -- the word "Hello" in default color and "World" in red.
Question 10
Medium
What does this code log?
<ul id="list">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

<script>
const first = document.querySelector("#list li");
const all = document.querySelectorAll("#list li");
console.log(first.textContent);
console.log(all.length);
console.log(all[2].textContent);
</script>
querySelector returns the first match. querySelectorAll returns all. NodeList is zero-indexed.
One
3
Three
Question 11
Medium
What is logged?
<div id="box">Hello</div>

<script>
const box = document.getElementById("box");
box.style.color = "white";
box.style.backgroundColor = "#a855f7";
box.style.padding = "20px";
console.log(box.style.color);
console.log(box.style.backgroundColor);
console.log(box.style.margin);
</script>
element.style only reads inline styles, not styles from a stylesheet.
white
#a855f7
(empty string)
Question 12
Medium
What does this code log?
<p id="demo">Hello</p>

<script>
const p = document.getElementById("demo");
p.textContent = "<strong>Bold</strong>";
console.log(p.textContent);
console.log(p.innerHTML);
</script>
textContent does not parse HTML. It treats everything as plain text.
<strong>Bold</strong>
&lt;strong&gt;Bold&lt;/strong&gt;
Question 13
Hard
What is logged?
<div class="box" data-color="red">A</div>
<div class="box" data-color="blue">B</div>
<div class="box" data-color="red">C</div>

<script>
const redBoxes = document.querySelectorAll('.box[data-color="red"]');
console.log(redBoxes.length);
redBoxes.forEach(function(box) {
  console.log(box.textContent);
});
</script>
Attribute selectors filter by attribute value.
2
A
C
Question 14
Hard
What is logged?
<div id="wrapper">
  <p class="text">First</p>
  <p class="text highlight">Second</p>
  <p class="text">Third</p>
</div>

<script>
const el = document.querySelector(".text.highlight");
console.log(el.textContent);

const notFound = document.querySelector(".text.missing");
console.log(notFound);
</script>
querySelector returns null when no element matches the selector.
Second
null
Question 15
Hard
What does the paragraph display on the page after this code runs?
<p id="info">Name: <span id="name">Guest</span></p>

<script>
const nameSpan = document.getElementById("name");
nameSpan.textContent = "Aarav";

const info = document.getElementById("info");
console.log(info.textContent);
console.log(info.innerHTML);
</script>
Changing the span's text changes it inside the parent too.
Console logs:
Name: Aarav
Name: <span id="name">Aarav</span>
Question 16
Hard
What is logged?
<div id="box" class="card">Hello</div>

<script>
const box = document.getElementById("box");
box.classList.add("active", "large");
console.log(box.className);

box.classList.remove("card", "large");
console.log(box.className);

box.classList.toggle("hidden");
box.classList.toggle("active");
console.log(box.className);
</script>
Track the classes step by step. add/remove can take multiple arguments.
card active large
active
hidden
Question 17
Hard
What does this code log?
<select id="color">
  <option value="red">Red</option>
  <option value="green" selected>Green</option>
  <option value="blue">Blue</option>
</select>

<script>
const select = document.getElementById("color");
console.log(select.value);
console.log(select.selectedIndex);
select.value = "blue";
console.log(select.value);
console.log(select.selectedIndex);
</script>
The selected attribute determines the initial value. selectedIndex is zero-based.
green
1
blue
2
Question 18
Easy
What is logged?
<a id="link" href="https://example.com">Visit</a>

<script>
const link = document.getElementById("link");
console.log(link.textContent);
console.log(link.getAttribute("href"));
</script>
textContent gives the visible text. getAttribute reads the attribute value.
Visit
https://example.com

Mixed & Application Questions

Question 1
Easy
What does this code do?
<button id="btn">Click Me</button>

<script>
const btn = document.getElementById("btn");
btn.textContent = "Clicked!";
btn.style.backgroundColor = "green";
btn.style.color = "white";
</script>
The code runs immediately, not on click.
The button immediately shows "Clicked!" with a green background and white text. No click is needed because the code runs as soon as the page loads.
Question 2
Easy
What does this code log?
<div id="box">Hello</div>

<script>
const box = document.querySelector("#box");
const box2 = document.getElementById("box");
console.log(box === box2);
</script>
Both methods select the same element.
true
Question 3
Medium
What is logged?
<div id="container">
  <span class="tag">HTML</span>
  <span class="tag">CSS</span>
  <span class="tag">JavaScript</span>
</div>

<script>
const tags = document.querySelectorAll(".tag");
const arr = Array.from(tags);
const result = arr.map(tag => tag.textContent.toUpperCase());
console.log(result);
</script>
Array.from converts a NodeList to an array, enabling map().
["HTML", "CSS", "JAVASCRIPT"]
Question 4
Medium
After this code runs, what CSS classes does the div have?
<div id="card" class="card">Hello</div>

<script>
const card = document.getElementById("card");
card.classList.add("active");
card.classList.add("active");  // Adding same class again
card.classList.toggle("card");
card.classList.toggle("new");
console.log(card.className);
</script>
Adding a class that already exists does nothing. Toggle removes if present, adds if missing.
active new
Question 5
Medium
What does this code log?
<input type="checkbox" id="agree">

<script>
const checkbox = document.getElementById("agree");
console.log(checkbox.checked);
console.log(checkbox.value);
checkbox.checked = true;
console.log(checkbox.checked);
</script>
Checkboxes have a checked property (boolean) and a value property.
false
on
true
Question 6
Medium
What does this code log?
<ul id="list">
  <li>Aarav</li>
  <li>Priya</li>
  <li>Rohan</li>
</ul>

<script>
const items = document.querySelectorAll("#list li");
let names = "";
items.forEach(function(item, index) {
  names += index + ": " + item.textContent + " ";
});
console.log(names.trim());
</script>
forEach on a NodeList provides the element and its index.
0: Aarav 1: Priya 2: Rohan
Question 7
Hard
What does this code log?
<div id="outer">
  <p id="inner">Hello</p>
</div>

<script>
const outer = document.getElementById("outer");
const inner = document.getElementById("inner");

outer.innerHTML = "<p id='inner'>Replaced</p>";

const innerAgain = document.getElementById("inner");
console.log(inner.textContent);
console.log(innerAgain.textContent);
console.log(inner === innerAgain);
</script>
innerHTML destroys old elements and creates new ones. The old reference still points to the old element.
Hello
Replaced
false
Question 8
Hard
What does this code log?
<div id="box" style="color: red; font-size: 20px;">Text</div>

<script>
const box = document.getElementById("box");
console.log(box.style.color);
console.log(box.style.fontSize);
box.style.cssText = "background: blue;";
console.log(box.style.color);
console.log(box.style.cssText);
</script>
Setting style.cssText replaces ALL inline styles with the new string.
red
20px
(empty string)
background: blue;
Question 9
Easy
What is the difference between textContent and innerHTML?
One treats the content as plain text, the other as HTML.
textContent gets or sets the plain text inside an element. It ignores HTML tags and treats everything as text. innerHTML gets or sets the HTML content, parsing and rendering any HTML tags. For security, use textContent when dealing with user input to prevent XSS attacks.
Question 10
Medium
Why should you avoid using innerHTML with user input?
Think about what happens if a user types a script tag.
Using innerHTML with user input creates a Cross-Site Scripting (XSS) vulnerability. If a user enters <img src=x onerror="alert('hacked')">, innerHTML will parse it as real HTML and execute the JavaScript. Always use textContent for user input, which treats everything as safe plain text.
Question 11
Medium
What is the difference between querySelector and getElementById?
Think about what selectors each one accepts.
getElementById only selects by ID and takes the ID string without the # symbol. querySelector accepts any CSS selector (#id, .class, tag, [attribute], combinations). getElementById is slightly faster for ID lookups, but querySelector is more flexible and is the modern approach.
Question 12
Hard
What does this code log?
<p id="text" class="blue bold">Hello</p>

<script>
const p = document.getElementById("text");
const classes = [...p.classList];
console.log(classes);
console.log(typeof p.classList);
console.log(Array.isArray(p.classList));
console.log(Array.isArray(classes));
</script>
classList is a DOMTokenList, not an array. Spreading converts it.
["blue", "bold"]
object
false
true

Multiple Choice Questions

MCQ 1
Which method selects an element by its ID?
  • A. document.querySelector()
  • B. document.getElementById()
  • C. document.getElementsByClassName()
  • D. document.getElement()
Answer: B
B is correct. document.getElementById() selects a single element by its unique ID. Option A uses CSS selectors. Option C selects by class name. Option D does not exist.
MCQ 2
What does document.querySelectorAll('.item') return?
  • A. A single element
  • B. An array
  • C. A NodeList
  • D. undefined
Answer: C
C is correct. querySelectorAll returns a NodeList containing all matching elements. A NodeList is array-like but not a true array. It supports forEach but not map or filter directly.
MCQ 3
Which property should you use to safely display user input on a page?
  • A. innerHTML
  • B. outerHTML
  • C. textContent
  • D. innerText
Answer: C
C is correct. textContent treats the input as plain text and does not parse HTML tags, preventing XSS attacks. innerHTML would parse and execute any HTML or scripts in the input.
MCQ 4
How do you read the current value of a text input field?
  • A. input.textContent
  • B. input.innerHTML
  • C. input.text
  • D. input.value
Answer: D
D is correct. The .value property reads and sets the current value of input, textarea, and select elements. textContent and innerHTML are for reading content of regular HTML elements, not form inputs.
MCQ 5
What does getElementById return if no element matches?
  • A. undefined
  • B. false
  • C. null
  • D. An empty string
Answer: C
C is correct. getElementById returns null when no element with that ID exists. This is important to check before using the element to avoid TypeError.
MCQ 6
How do you write background-color in JavaScript's style property?
  • A. background-color
  • B. backgroundColor
  • C. backgroundcolor
  • D. BACKGROUND_COLOR
Answer: B
B is correct. CSS property names with hyphens are converted to camelCase in JavaScript. Remove the hyphen and capitalize the next letter: background-color becomes backgroundColor.
MCQ 7
What does classList.toggle('active') do?
  • A. Always adds the 'active' class
  • B. Always removes the 'active' class
  • C. Adds the class if missing, removes it if present
  • D. Checks if the class exists
Answer: C
C is correct. toggle() adds the class if it is not present and removes it if it is. It returns true if the class was added and false if it was removed.
MCQ 8
Which selector would match <li class='item active'> but NOT <li class='item'>?
  • A. document.querySelector('.item')
  • B. document.querySelector('.active')
  • C. document.querySelector('.item.active')
  • D. document.querySelector('.item .active')
Answer: C
C is correct. .item.active (no space) selects elements with BOTH classes. .item .active (with space) selects .active elements that are descendants of .item elements. Option A matches both because both have class 'item'.
MCQ 9
What is the security risk of using innerHTML with user input?
  • A. It is slow
  • B. It can cause Cross-Site Scripting (XSS) attacks
  • C. It crashes the browser
  • D. It only works in Chrome
Answer: B
B is correct. XSS (Cross-Site Scripting) occurs when user input containing malicious HTML or JavaScript is inserted into the page via innerHTML. The browser executes the injected code, which can steal data or hijack sessions.
MCQ 10
How do you convert a NodeList to a real array?
  • A. nodeList.toArray()
  • B. Array.from(nodeList) or [...nodeList]
  • C. nodeList.array()
  • D. new Array(nodeList)
Answer: B
B is correct. Array.from(nodeList) and the spread operator [...nodeList] both convert a NodeList to a real array, enabling methods like map, filter, and reduce.
MCQ 11
What does element.style.fontSize read?
  • A. The font-size from any CSS source
  • B. The font-size from the stylesheet only
  • C. The font-size set as an inline style only
  • D. The computed font-size
Answer: C
C is correct. element.style only reads inline styles (styles set directly on the element via the style attribute or JS). To get the computed style from all CSS sources, use getComputedStyle(element).
MCQ 12
What happens when you set element.innerHTML = ''?
  • A. The element is removed from the DOM
  • B. All child elements inside are removed
  • C. Nothing happens
  • D. An error is thrown
Answer: B
B is correct. Setting innerHTML to an empty string removes all child nodes (elements and text) inside the element. The element itself remains in the DOM, just empty.
MCQ 13
What does setAttribute('disabled', '') do to a button?
  • A. Nothing, because the value is empty
  • B. Removes the disabled attribute
  • C. Disables the button (boolean attributes are enabled by their presence)
  • D. Throws an error
Answer: C
C is correct. HTML boolean attributes like disabled, checked, and readonly are active simply by being present on the element. The value does not matter. Even disabled="" disables the button.
MCQ 14
Which method returns the styles actually applied to an element (including styles from CSS files)?
  • A. element.style
  • B. element.currentStyle
  • C. getComputedStyle(element)
  • D. element.getStyle()
Answer: C
C is correct. getComputedStyle(element) returns the final computed values of all CSS properties, including those from stylesheets, inherited styles, and browser defaults. element.style only reads inline styles.
MCQ 15
What is the difference between removeAttribute('disabled') and element.disabled = false?
  • A. They are identical
  • B. removeAttribute removes the HTML attribute; .disabled = false sets the property to false. Both enable the element.
  • C. Only removeAttribute works
  • D. Only .disabled = false works
Answer: B
B is correct. removeAttribute removes the attribute from the HTML markup. Setting the property to false changes the element's behavior. Both effectively enable the element, but they work at different levels (attribute vs. property).
MCQ 16
Which selector selects the first child <li> inside #list?
  • A. document.querySelector('#list li')
  • B. document.querySelector('#list > li:last-child')
  • C. document.querySelectorAll('#list li')
  • D. document.querySelector('#list')
Answer: A
A is correct. querySelector returns the first matching element. #list li matches all li elements inside #list, but querySelector only returns the first one.
MCQ 17
What does element.className return?
  • A. A DOMTokenList of all classes
  • B. The first class name only
  • C. A string of all class names separated by spaces
  • D. An array of class names
Answer: C
C is correct. className returns a string like "card active large". For individual class manipulation, use classList which provides add, remove, toggle, and contains methods.
MCQ 18
Why should you place <script> tags at the end of the <body>?
  • A. It makes JavaScript run faster
  • B. It ensures all HTML elements exist before the script tries to access them
  • C. It is required by the HTML specification
  • D. It prevents caching
Answer: B
B is correct. The browser parses HTML top to bottom. If a script in the <head> tries to access an element in the body, the element does not exist yet and getElementById returns null. Placing scripts at the end ensures all elements are loaded.

Coding Challenges

Challenge 1: Live Character Counter

Easy
Create an HTML page with a textarea and a paragraph below it. As the user types in the textarea, show the character count in the paragraph. Example: 'Characters: 15'.
Sample Input
(No input required -- type in the textarea)
Sample Output
Characters: 0 (updates as you type)
Use the 'input' event on the textarea and textContent to update the count.
<!DOCTYPE html>
<html>
<body>
  <textarea id="text" rows="4" cols="40" placeholder="Start typing..."></textarea>
  <p id="count">Characters: 0</p>
  <script>
    const textarea = document.getElementById("text");
    const countDisplay = document.getElementById("count");
    textarea.addEventListener("input", function() {
      countDisplay.textContent = "Characters: " + textarea.value.length;
    });
  </script>
</body>
</html>

Challenge 2: Profile Card Builder

Easy
Create a form with fields for name, age, and hobby. When a 'Generate Card' button is clicked, display a styled card below the form showing the entered information. Use textContent for security.
Sample Input
Name: Aarav, Age: 15, Hobby: Coding
Sample Output
A card appears showing: Name: Aarav, Age: 15, Hobby: Coding
Use getElementById to get input values. Use textContent (not innerHTML) to display user input.
<!DOCTYPE html>
<html>
<head>
  <style>
    .card { padding: 16px; border: 2px solid #a855f7; border-radius: 8px; margin-top: 16px; display: none; }
    .card.visible { display: block; }
  </style>
</head>
<body>
  <input type="text" id="name" placeholder="Name">
  <input type="number" id="age" placeholder="Age">
  <input type="text" id="hobby" placeholder="Hobby">
  <button id="generate">Generate Card</button>
  <div class="card" id="card">
    <p id="card-name"></p>
    <p id="card-age"></p>
    <p id="card-hobby"></p>
  </div>
  <script>
    document.getElementById("generate").addEventListener("click", function() {
      document.getElementById("card-name").textContent = "Name: " + document.getElementById("name").value;
      document.getElementById("card-age").textContent = "Age: " + document.getElementById("age").value;
      document.getElementById("card-hobby").textContent = "Hobby: " + document.getElementById("hobby").value;
      document.getElementById("card").classList.add("visible");
    });
  </script>
</body>
</html>

Challenge 3: Color Theme Switcher

Medium
Create a page with three buttons: 'Purple', 'Teal', 'Amber'. Clicking each button should change the page's background color and text color using classList. Define three CSS classes (.theme-purple, .theme-teal, .theme-amber) with different color schemes. Only one theme should be active at a time.
Sample Input
(Click buttons)
Sample Output
Background and text colors change based on which button is clicked.
Use classList.add and classList.remove. Do not use inline styles. Remove the previous theme class before adding the new one.
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial; padding: 20px; transition: all 0.3s; }
    .theme-purple { background: #a855f7; color: white; }
    .theme-teal { background: #06b6d4; color: white; }
    .theme-amber { background: #f59e0b; color: #1a1a1a; }
  </style>
</head>
<body>
  <h1>Theme Switcher</h1>
  <button id="purple">Purple</button>
  <button id="teal">Teal</button>
  <button id="amber">Amber</button>
  <script>
    const themes = ["theme-purple", "theme-teal", "theme-amber"];
    function setTheme(theme) {
      themes.forEach(function(t) { document.body.classList.remove(t); });
      document.body.classList.add(theme);
    }
    document.getElementById("purple").addEventListener("click", function() { setTheme("theme-purple"); });
    document.getElementById("teal").addEventListener("click", function() { setTheme("theme-teal"); });
    document.getElementById("amber").addEventListener("click", function() { setTheme("theme-amber"); });
  </script>
</body>
</html>

Challenge 4: Student List Filter

Medium
Create an HTML page with a list of 6 student names (as li elements with a class 'student'). Add a text input at the top. As the user types, hide students whose names do not match the search text (case-insensitive). Use classList to add/remove a 'hidden' class.
Sample Input
Type 'pr' in the search box
Sample Output
Only 'Priya' and 'Pramod' remain visible. Other students are hidden.
Use querySelectorAll, forEach, textContent.toLowerCase(), and classList.toggle or add/remove.
<!DOCTYPE html>
<html>
<head>
  <style>
    .hidden { display: none; }
    li { padding: 8px; font-size: 18px; }
  </style>
</head>
<body>
  <input type="text" id="search" placeholder="Search students...">
  <ul>
    <li class="student">Aarav</li>
    <li class="student">Priya</li>
    <li class="student">Rohan</li>
    <li class="student">Meera</li>
    <li class="student">Pramod</li>
    <li class="student">Kavya</li>
  </ul>
  <script>
    const search = document.getElementById("search");
    const students = document.querySelectorAll(".student");
    search.addEventListener("input", function() {
      const query = search.value.toLowerCase();
      students.forEach(function(student) {
        const name = student.textContent.toLowerCase();
        if (name.includes(query)) {
          student.classList.remove("hidden");
        } else {
          student.classList.add("hidden");
        }
      });
    });
  </script>
</body>
</html>

Challenge 5: Attribute Inspector

Medium
Create a page with an image element that has src, alt, width, and a data-photographer attribute. Add four buttons: 'Show src', 'Show alt', 'Change alt', 'Remove data-photographer'. Each button should perform its action and display the result in a paragraph below using getAttribute, setAttribute, and removeAttribute.
Sample Input
(Click buttons)
Sample Output
Clicking 'Show src' displays the image source URL. Clicking 'Remove data-photographer' removes that attribute.
Use getAttribute, setAttribute, removeAttribute, and hasAttribute.
<!DOCTYPE html>
<html>
<body>
  <img id="photo" src="https://placehold.co/200x150" alt="A scenic view" width="200" data-photographer="Aarav">
  <br>
  <button id="show-src">Show src</button>
  <button id="show-alt">Show alt</button>
  <button id="change-alt">Change alt</button>
  <button id="remove-data">Remove data-photographer</button>
  <p id="output"></p>
  <script>
    const img = document.getElementById("photo");
    const output = document.getElementById("output");
    document.getElementById("show-src").addEventListener("click", function() {
      output.textContent = "src: " + img.getAttribute("src");
    });
    document.getElementById("show-alt").addEventListener("click", function() {
      output.textContent = "alt: " + img.getAttribute("alt");
    });
    document.getElementById("change-alt").addEventListener("click", function() {
      img.setAttribute("alt", "Updated scenic view");
      output.textContent = "alt changed to: " + img.getAttribute("alt");
    });
    document.getElementById("remove-data").addEventListener("click", function() {
      img.removeAttribute("data-photographer");
      output.textContent = "Has data-photographer: " + img.hasAttribute("data-photographer");
    });
  </script>
</body>
</html>

Challenge 6: Interactive Grade Card

Hard
Build a grade card page. Create a table with 5 subjects (Maths, Science, English, Hindi, Computer) and input fields for marks. Add a 'Calculate' button. When clicked: (1) Read all marks from inputs. (2) Calculate total and percentage. (3) Display results below the table. (4) If percentage >= 90, add a 'distinction' class to the result div (gold background). If >= 60, add 'pass' class (green). Otherwise add 'fail' class (red). Use classList for styling.
Sample Input
Maths: 90, Science: 85, English: 78, Hindi: 92, Computer: 95
Sample Output
Total: 440/500, Percentage: 88%, Class: pass (green background)
Use querySelectorAll to get all input values. Use classList for conditional styling. Do not use inline styles.
<!DOCTYPE html>
<html>
<head>
  <style>
    .distinction { background: #fef3c7; border: 2px solid #f59e0b; padding: 16px; border-radius: 8px; }
    .pass { background: #d1fae5; border: 2px solid #10b981; padding: 16px; border-radius: 8px; }
    .fail { background: #fecaca; border: 2px solid #ef4444; padding: 16px; border-radius: 8px; }
    input { width: 60px; padding: 4px; }
  </style>
</head>
<body>
  <h2>Grade Card</h2>
  <table>
    <tr><td>Maths:</td><td><input type="number" class="mark" max="100"></td></tr>
    <tr><td>Science:</td><td><input type="number" class="mark" max="100"></td></tr>
    <tr><td>English:</td><td><input type="number" class="mark" max="100"></td></tr>
    <tr><td>Hindi:</td><td><input type="number" class="mark" max="100"></td></tr>
    <tr><td>Computer:</td><td><input type="number" class="mark" max="100"></td></tr>
  </table>
  <button id="calc">Calculate</button>
  <div id="result"></div>
  <script>
    document.getElementById("calc").addEventListener("click", function() {
      const inputs = document.querySelectorAll(".mark");
      let total = 0;
      inputs.forEach(function(input) { total += Number(input.value) || 0; });
      const percentage = (total / 500) * 100;
      const result = document.getElementById("result");
      result.classList.remove("distinction", "pass", "fail");
      result.textContent = "Total: " + total + "/500, Percentage: " + percentage.toFixed(1) + "%";
      if (percentage >= 90) { result.classList.add("distinction"); }
      else if (percentage >= 60) { result.classList.add("pass"); }
      else { result.classList.add("fail"); }
    });
  </script>
</body>
</html>

Challenge 7: Bulk Style Editor

Hard
Create a page with 5 paragraph elements with class 'editable'. Add a control panel with: (1) a color input for text color, (2) a range input (12-36) for font size, (3) a checkbox for bold. As the user changes any control, ALL paragraphs should update their style immediately. Use querySelectorAll and forEach.
Sample Input
Set color to red, font size to 24, check bold
Sample Output
All 5 paragraphs turn red, 24px, bold simultaneously.
Use querySelectorAll to get all paragraphs. Use the input event on controls. You may use inline styles here since the values are dynamic.
<!DOCTYPE html>
<html>
<body>
  <div>
    <label>Color: <input type="color" id="color" value="#000000"></label>
    <label>Size: <input type="range" id="size" min="12" max="36" value="16"> <span id="size-display">16px</span></label>
    <label><input type="checkbox" id="bold"> Bold</label>
  </div>
  <p class="editable">Paragraph 1 by Aarav</p>
  <p class="editable">Paragraph 2 by Priya</p>
  <p class="editable">Paragraph 3 by Rohan</p>
  <p class="editable">Paragraph 4 by Meera</p>
  <p class="editable">Paragraph 5 by Kavya</p>
  <script>
    const paragraphs = document.querySelectorAll(".editable");
    const colorInput = document.getElementById("color");
    const sizeInput = document.getElementById("size");
    const boldInput = document.getElementById("bold");
    const sizeDisplay = document.getElementById("size-display");
    function updateStyles() {
      const color = colorInput.value;
      const size = sizeInput.value + "px";
      const weight = boldInput.checked ? "bold" : "normal";
      sizeDisplay.textContent = size;
      paragraphs.forEach(function(p) {
        p.style.color = color;
        p.style.fontSize = size;
        p.style.fontWeight = weight;
      });
    }
    colorInput.addEventListener("input", updateStyles);
    sizeInput.addEventListener("input", updateStyles);
    boldInput.addEventListener("change", updateStyles);
  </script>
</body>
</html>

Challenge 8: Accordion FAQ

Hard
Build an FAQ accordion. Create 4 question-answer pairs where each question is in a div with class 'question' and the answer is in a div with class 'answer'. Initially all answers are hidden (display: none via a CSS class). Clicking a question toggles its answer visibility. Only one answer should be visible at a time -- clicking a new question hides the previously open answer.
Sample Input
(Click on questions)
Sample Output
Clicking 'What is JavaScript?' shows its answer and hides any other open answer.
Use querySelectorAll, forEach, classList.toggle, and classList.remove. Do not use inline styles.
<!DOCTYPE html>
<html>
<head>
  <style>
    .question { padding: 12px; background: #f3f4f6; cursor: pointer; border-bottom: 1px solid #ddd; font-weight: bold; }
    .answer { padding: 12px; display: none; }
    .answer.open { display: block; }
  </style>
</head>
<body>
  <h2>FAQ</h2>
  <div class="faq">
    <div class="question">What is JavaScript?</div>
    <div class="answer">JavaScript is a programming language that makes websites interactive.</div>
    <div class="question">What is the DOM?</div>
    <div class="answer">The DOM is a tree of objects representing your HTML page.</div>
    <div class="question">What is querySelector?</div>
    <div class="answer">querySelector selects the first element matching a CSS selector.</div>
    <div class="question">What is classList?</div>
    <div class="answer">classList provides methods to add, remove, and toggle CSS classes.</div>
  </div>
  <script>
    const questions = document.querySelectorAll(".question");
    questions.forEach(function(q) {
      q.addEventListener("click", function() {
        const answer = q.nextElementSibling;
        const isOpen = answer.classList.contains("open");
        document.querySelectorAll(".answer").forEach(function(a) { a.classList.remove("open"); });
        if (!isOpen) { answer.classList.add("open"); }
      });
    });
  </script>
</body>
</html>

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn web development with a live mentor?

Explore our Frontend Masterclass