Sample questions
Question 1Easy
What does document.querySelector(".item") return?
- The element whose id attribute is item
- The first element with class item, or null
- An array of every element with class item
- A NodeList of all elements with class item
Answer: B. The first element with class item, or null
Explanation
querySelector returns the first element matching the CSS selector, or null if none matches. querySelectorAll returns all matches.
Step-by-step solution
- document.querySelector() takes any valid CSS selector string and searches the whole document for a matching element.
- ".item" is a CSS class selector, matching any element that has "item" in its class list.
- querySelector() specifically returns only the FIRST matching element found (in document order), or null if absolutely no element matches.
Why the other options are wrong
- A. Matching an id attribute would require a "#item" selector (with a hash), not ".item" (with a dot), which specifically targets the class attribute instead.
- C. Returning an array of every matching element describes neither querySelector() (which returns just one element) nor querySelectorAll() (which returns a NodeList, not a true JavaScript array).
- D. A NodeList of ALL matching elements is what querySelectorAll(".item") would return instead; querySelector() (singular) specifically stops at just the first match.
Tip: Singular 'querySelector' = first match only (or null); plural 'querySelectorAll' = ALL matches, as a NodeList.
Question 2Easy
What does event.preventDefault() do in a form's submit handler?
- Cancels the browser's default action, such as submitting and reloading
- Removes the submit listener so it will not run again on later submits
- Stops the event from bubbling up to the form's parent elements
- Stops other submit listeners on the same form element from running
Answer: A. Cancels the browser's default action, such as submitting and reloading
Explanation
preventDefault cancels the browser's default behaviour. Stopping propagation to ancestors is what stopPropagation does.
Step-by-step solution
- Many DOM elements have built-in 'default actions' that the browser automatically performs in response to certain events - for a form's submit event, that default action is actually submitting the form data and (traditionally) reloading/navigating the page.
- event.preventDefault(), called inside an event handler, specifically cancels ONLY that browser-default behaviour for the current event.
- So calling it inside a submit handler stops the form from actually submitting/reloading the page, letting your own JavaScript code (like custom validation or an AJAX request) take over instead.
Why the other options are wrong
- B. preventDefault() does not remove or disable the event LISTENER itself; the same handler will still run again on the NEXT submit event, since only the current event's default browser action was cancelled, not the listener's future triggering.
- C. Stopping an event from bubbling UP to parent elements is what event.stopPropagation() does, a distinctly different method with a different purpose than preventDefault().
- D. Stopping OTHER listeners attached to the SAME element from running is what event.stopImmediatePropagation() does; preventDefault() only cancels the browser's own default action, without affecting any other registered listeners at all.
Tip: preventDefault() = stop the BROWSER's default action. stopPropagation() = stop the event from reaching OTHER elements. These solve different problems, and you sometimes need both.
Question 3Easy
Which method attaches a click handler without replacing handlers that are already attached?
element.onclick = fnelement.click(fn)element.setAttribute("onclick", fn)element.addEventListener("click", fn)
Answer: D. element.addEventListener("click", fn)
Explanation
addEventListener can register several listeners for the same event. Assigning onclick replaces the previous handler.
Step-by-step solution
- There are multiple ways to attach an event handler to a DOM element, with different behaviours around multiple handlers.
- Setting element.onclick = fn directly REPLACES any previously assigned onclick handler, since it's just a plain property assignment (only one value can be stored there at a time).
- element.addEventListener("click", fn) instead REGISTERS an additional listener without removing any existing ones, allowing multiple independent click handlers to coexist on the same element.
Why the other options are wrong
- A. element.onclick = fn specifically OVERWRITES (replaces) any previous handler assigned the same way, which is the opposite of what's being asked for here.
- B. element.click(fn) isn't valid syntax for attaching a handler at all; element.click() (with no useful argument like this) is actually a method that simulates a user click on the element.
- C. element.setAttribute("onclick", fn) would set the onclick HTML attribute to a STRING representation of fn (not meaningfully usable as a real function reference), and even if it worked as intended, inline attribute handlers have their own overwrite-on-reassignment behaviour too.
Tip: Prefer addEventListener over direct onclick/onX property assignment whenever more than one piece of code might need to react to the same event.
Question 4Medium
Which is the safer way to put user-provided text into an element to avoid script injection?
- Assign it to textContent
- Assign it to innerHTML
- Assign it to outerHTML
- Use document.write after load
Answer: A. Assign it to textContent
Explanation
textContent inserts the string as plain text, never parsing it as HTML.
Step-by-step solution
- innerHTML parses markup.
- textContent treats everything as text.
Why the other options are wrong
- B. innerHTML parses the string as HTML and can run injected markup.
- C. outerHTML also parses markup.
- D. document.write parses HTML and can wipe the page.
Question 5Medium
A click listener is attached to a parent list element, and the list items are added later dynamically. Which technique makes clicks on the new items work without extra listeners?
- Calling stopPropagation on every item
- Event delegation: listen on the parent and check event.target
- Using innerHTML to attach inline handlers on each render only
- Setting the parent listener to run only once
Answer: B. Event delegation: listen on the parent and check event.target
Explanation
Click events bubble up, so one listener on the parent can inspect event.target (or closest) and react for items that exist now or are added later.
Step-by-step solution
- Events bubble from the item to the parent.
- The parent listener reads event.target.
- New items work automatically.
Why the other options are wrong
- A. That would stop the event reaching the parent listener.
- C. It requires re-attaching and does not scale, delegation is simpler.
- D. That would handle just a single click.
Tip: Use event.target.closest(selector) to find the item.
Question 6Medium
Why is element.textContent = userInput safer than element.innerHTML = userInput?
- textContent inserts the input as literal text, so no HTML is parsed
- textContent automatically escapes SQL before it reaches the server
- textContent is faster, and speed is what prevents injection attacks
- innerHTML only works on div elements and fails silently elsewhere
Answer: A. textContent inserts the input as literal text, so no HTML is parsed
Explanation
innerHTML parses its value as HTML, which can enable cross-site scripting (XSS) with untrusted input. textContent treats it as plain text.
Step-by-step solution
- element.innerHTML = userInput takes the string userInput and actively PARSES it as raw HTML markup, inserting whatever tags, scripts, or attributes it contains directly into the live page.
- If userInput comes from an untrusted source (like user-submitted text) and happens to contain malicious markup (like a <script> tag or an onerror handler), innerHTML will execute/render that malicious content - this is a classic cross-site scripting (XSS) vulnerability.
- element.textContent = userInput, by contrast, always treats the ENTIRE string as plain, literal text - it never parses any part of it as HTML tags or attributes, so any embedded markup is simply displayed as harmless, inert text.
Why the other options are wrong
- B. textContent has nothing to do with SQL or server-side database queries at all; it's a purely client-side, browser DOM property concerned with how a string is rendered as either plain text or (in innerHTML's case) parsed HTML.
- C. Speed/performance is not the real security-relevant difference here, and claiming 'speed prevents injection' misunderstands the actual mechanism; the real protection comes specifically from textContent NOT parsing its input as HTML at all, regardless of how fast or slow either method runs.
- D. Both innerHTML and textContent work on virtually any element type, not specifically or exclusively on div elements; this option misstates a basic, unrelated fact about how these properties function.
Tip: Default to textContent for inserting plain text; reach for innerHTML only when you specifically need to insert TRUSTED markup, and never with raw, unescaped user input.
Question 7Medium
A <ul> list has 1,000 <li> items that are added and removed dynamically. What is the usual way to handle clicks on them efficiently?
- Attach a separate click listener to every
<li> when it is created - Use setInterval to poll each
<li> for its current clicked state - Add an inline onclick attribute to each
<li> in the HTML markup - Attach one listener to the parent
<ul> and check event.target
Answer: D. Attach one listener to the parent <ul> and check event.target
Explanation
Event delegation relies on bubbling: one listener on a common ancestor handles events from all current and future children.
Step-by-step solution
- Attaching a separate listener to each of 1,000 individual elements (especially ones that get created/destroyed dynamically) is wasteful in both memory and setup effort, and new elements added later wouldn't automatically get a listener either.
- DOM events 'bubble' upward by default: a click on a child also fires as a click event on each of its ancestor elements, all the way up to the document and beyond.
- Event delegation takes advantage of this: you attach just ONE listener to the parent
<ul>, and inside it, check event.target (the actual element that was originally clicked) to figure out which specific <li> was clicked - this single listener automatically covers any future elements too, even ones added after the listener was set up.
Why the other options are wrong
- A. Attaching a separate listener to every individual
<li> is exactly the wasteful, inefficient approach that event delegation is specifically designed to avoid - and it also fails to automatically cover any new elements added later. - B. Using setInterval to repeatedly POLL every item for its click state is a crude, inefficient, and non-standard way to detect clicks, completely bypassing the browser's native, efficient event system.
- C. Adding an inline onclick attribute directly in the HTML markup for every single
<li> has the SAME scaling problem as attaching 1,000 separate individual listeners, and similarly fails to automatically cover future dynamically-added items.
Question 8Hard
A parent and child both have click listeners in the default (bubbling) phase. The child handler calls event.stopPropagation(). Clicking the child, what happens?
- Both run, the parent first
- Both run, the child first
- Only the child handler runs; the parent handler is not called
- Neither runs because the event is cancelled
Answer: C. Only the child handler runs; the parent handler is not called
Explanation
Bubbling goes from the target up; stopPropagation in the child stops the event travelling to the parent.
Step-by-step solution
- The click starts at the child.
- The child handler calls stopPropagation.
- The event never reaches the parent.
Why the other options are wrong
- A. Bubbling runs from the child upward, and stopPropagation halts it.
- B. stopPropagation prevents the parent from running.
- D. stopPropagation does not cancel the child handler itself.
Tip: preventDefault stops the default action; stopPropagation stops travel.
Question 9Hard
Calling addEventListener("click", fn, true) on a parent element means fn runs:
- In the bubbling phase, after the listeners on the target element
- Only when the parent element itself is the one that was clicked
- Only once, after which the listener is removed automatically
- In the capture phase, before listeners on the target element
Answer: D. In the capture phase, before listeners on the target element
Explanation
The third argument true (or {capture: true}) registers the listener for the capture phase, which travels from the window down to the target before the bubble phase goes back up.
Step-by-step solution
- DOM events generally travel through a page in two distinct phases: first a 'capture' phase, moving DOWN from the window through ancestor elements toward the actual target element, and then a 'bubble' phase, moving back UP from the target through its ancestors again.
- addEventListener's third argument controls WHICH of these two phases a particular listener gets attached to; passing true (or {capture: true}) means the listener fires during the CAPTURE phase.
- Since capture happens BEFORE the event even reaches its actual target (and before the later bubble phase runs listeners there too), a capture-phase listener on a parent fires before any listeners on the target element itself, including ones in the bubble phase.
Why the other options are wrong
- A. Running 'after' target-element listeners, in the bubbling phase, describes the DEFAULT behaviour (when the third argument is omitted or false) - specifically the OPPOSITE of what passing true actually does.
- B. Capture-phase listeners on a parent element still fire for clicks anywhere within that parent's subtree, not just when the parent element ITSELF is the exact element clicked; capturing is about the event's travel path, not about restricting which specific element was clicked.
- C. There's nothing inherently 'one-time' about a capture-phase listener; it keeps firing on every matching event, just like any other listener, unless you also separately pass the {once: true} option.
Tip: addEventListener(type, fn) or addEventListener(type, fn, false) = bubble phase (the common default). addEventListener(type, fn, true) = capture phase (runs earlier, top-down).
Question 10Hard
What is a key difference between querySelectorAll(".x") and getElementsByClassName("x")?
- querySelectorAll returns only the first matching element
- querySelectorAll's result is a static snapshot; the other is live
- There is no difference; both return the same live collection
- getElementsByClassName accepts any CSS selector, including combinators
Answer: B. querySelectorAll's result is a static snapshot; the other is live
Explanation
A live HTMLCollection updates automatically as the DOM changes. The NodeList from querySelectorAll is a snapshot taken when it was called.
Step-by-step solution
- Both methods let you select elements matching a given CSS class, but they return fundamentally different kinds of results with different update behaviour.
document.querySelectorAll(".x") returns a STATIC NodeList: a fixed snapshot of whichever elements matched the selector at the exact moment the call was made, which does NOT automatically update if the DOM changes afterward.document.getElementsByClassName("x") instead returns a LIVE HTMLCollection: this collection automatically updates in real time as matching elements are added to or removed from the document, without needing to re-run the method.
Why the other options are wrong
- A. querySelectorAll() does NOT return only the first matching element; that limited behaviour belongs to the singular querySelector() instead - querySelectorAll (plural) always returns ALL matches, just as a static (non-live) collection.
- C. There IS a meaningful difference between the two: one returns a static snapshot (querySelectorAll) while the other returns a live, auto-updating collection (getElementsByClassName) - claiming no difference ignores this key distinction.
- D. getElementsByClassName() is specifically limited to class-name matching only (as its name suggests); it does NOT accept arbitrary, more complex CSS selectors or combinators the way querySelectorAll does.
Tip: When iterating and modifying the DOM at the same time, prefer the static snapshot from querySelectorAll() to avoid the live-collection 'shrinking while iterating' trap.
Practise all 10 questions free
The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.
Open this topic in the app →