JavaScript Intro to DOM (querySelector & textContent) Quiz

JavaScript
0 Passed
0% acceptance

Answer 40 questions covering DOM fundamentals, document structure, element selection with querySelector/querySelectorAll, CSS selector usage, reading and updating textContent, handling null results, safe DOM manipulation, and best practices.

40 Questions
~80 minutes
1

Question 1

What is the DOM?

A
A tree-like representation of the HTML document accessible via JavaScript
B
A CSS preprocessor
C
A database schema
D
A file system
2

Question 2

What does the document root node typically represent in browsers?

A
<html>
B
<body>
C
<head>
D
window
3

Question 3

Which property references the top-level document object?

A
window.document
B
document.window
C
global.documentRoot
D
dom
4

Question 4

What does document.body return?

A
The <body> element
B
All elements
C
A NodeList of children
D
null in fully loaded pages
5

Question 5

How are DOM nodes related to each other?

A
Through parent-child and sibling relationships forming a tree
B
In a flat array
C
Only parent references exist
D
Nodes are unrelated
6

Question 6

Which method finds the first matching element by CSS selector?

A
document.querySelector(selector)
B
document.getElementById(selector)
C
document.selectFirst(selector)
D
document.query(selector)
7

Question 7

What does document.querySelectorAll(".item") return?

A
A static NodeList of all elements with class item
B
A live HTMLCollection
C
An array
D
Only the first match
8

Question 8

Which CSS selector targets an element by ID?

A
#header
B
.header
C
header
D
*header
9

Question 9

What does this code log?

javascript
const title = document.querySelector('h1')
console.log(title)
console.log(title ? title.textContent : 'missing')
A
The h1 element reference and its text content if found
B
Always null
C
Throws if no h1 exists
D
Logs NodeList
10

Question 10

How do you iterate over querySelectorAll results?

javascript
const items = document.querySelectorAll('.item')
items.forEach(node => console.log(node.textContent))
A
NodeList has forEach in modern browsers to loop elements
B
NodeList must be converted to array first
C
forEach throws on NodeList
D
textContent is unavailable
11

Question 11

Which code handles missing elements gracefully?

javascript
const subtitle = document.querySelector('.subtitle')
if (subtitle) {
  console.log(subtitle.textContent)
}
A
Checks for null before accessing textContent to avoid errors
B
Throws due to if statement
C
subtitle always exists
D
textContent returns null
12

Question 12

What does this CSS selector match?

A
.card > .title selects .title elements that are direct children of .card
B
.card .title selects only direct children
C
.card + .title selects nested titles
D
.card.title selects two tags
13

Question 13

How do you select the element with attribute data-role="dialog"?

A
document.querySelector('[data-role="dialog"]')
B
document.querySelector('data-role=dialog')
C
document.querySelector('#data-role="dialog"')
D
document.getElementByDataRole("dialog")
14

Question 14

What does querySelectorAll return when no matches exist?

A
An empty NodeList
B
null
C
Throws ReferenceError
D
Undefined
15

Question 15

What is the difference between textContent and innerText?

A
textContent returns all text nodes regardless of CSS, innerText respects layout and CSS visibility
B
innerText is faster and standard
C
textContent strips whitespace differently
D
They are identical
16

Question 16

Which property updates an element’s textual content without parsing HTML?

javascript
const message = document.querySelector('#message')
message.textContent = 'Updated!'
A
textContent replaces the text contents safely
B
innerHTML
C
innerText always
D
nodeValue on the element
17

Question 17

How do you append additional text using textContent?

javascript
const statusEl = document.querySelector('.status')
statusEl.textContent += ' - Complete'
A
Concatenates strings; text nodes are updated entirely
B
Appends DOM nodes automatically
C
Throws TypeError
D
Requires innerHTML
18

Question 18

What does element.textContent = "" do?

A
Clears all text nodes inside the element
B
Removes the element
C
Throws error
D
Only hides text visually
19

Question 19

How do you safely update text on an element that might be null?

javascript
const alertBox = document.querySelector('.alert')
if (alertBox) {
  alertBox.textContent = 'Saved!'
}
A
Check for null before assignment to avoid runtime errors
B
textContent handles null automatically
C
Use alertBox.innerText only
D
Replace .alert with querySelectorAll
20

Question 20

Which scenario favors textContent over innerHTML?

A
Rendering user-generated text to avoid HTML injection
B
Inserting markup with tags
C
Adding event listeners
D
Changing classes
21

Question 21

What does this code output when the element has nested spans?

xml
<p id="info">Hello <span>World</span></p>
const el = document.querySelector('#info')
console.log(el.textContent)
A
Hello World
B
Hello
C
Only the span text
D
null
22

Question 22

How do you select the first <li> inside a .nav list?

javascript
const firstItem = document.querySelector('.nav li')
A
Combining selectors selects the first matching descendant li
B
Requires .nav > li
C
Cannot select li via querySelector
D
Returns NodeList
23

Question 23

What is a common pattern for caching DOM references?

A
Store query results in const variables to reuse them instead of querying repeatedly
B
Query inside every click handler without caching
C
Use global querySelector always
D
Only use IDs and no classes
24

Question 24

Why should you store NodeList results before manipulating them?

A
To iterate multiple times without re-querying and to avoid stale references
B
NodeLists mutate automatically
C
Required by browsers
D
NodeLists are arrays
25

Question 25

What is printed here?

javascript
const nodes = document.querySelectorAll('.item')
for (const node of nodes) {
  console.log(node.textContent.trim())
}
A
Each .item text, trimmed, logged in order
B
Throws because NodeList is not iterable
C
Only first item
D
Whitespace only
26

Question 26

Which code updates multiple elements with the same text?

javascript
document.querySelectorAll('.price').forEach(node => {
  node.textContent = '$9.99'
})
A
Sets textContent on every matched .price element
B
Only updates the first one
C
Requires innerHTML
D
Throws due to NodeList
27

Question 27

How do you ensure an element exists before using it in multiple functions?

A
Query once, store in const el, check el before passing around
B
Query repeatedly without checking
C
Wrap code in try/catch always
D
Use innerHTML
28

Question 28

Which code snippet demonstrates reading textContent safely with optional chaining?

javascript
const subtitleText = document.querySelector('.subtitle')?.textContent || ''
A
Returns textContent or empty string if element is null
B
Throws if element missing
C
Optional chaining unsupported
D
textContent is undefined always
29

Question 29

Why should you avoid direct innerHTML assignments when only text needs updating?

A
innerHTML parses HTML and is slower; textContent is safer and faster for plain text
B
innerHTML is deprecated
C
textContent doesn’t work
D
innerHTML doesn’t exist
30

Question 30

What is a safe approach when manipulating user-generated text?

A
Insert it via textContent to prevent user HTML from executing
B
Use innerHTML so formatting is preserved
C
Use eval on text
D
Use document.write
31

Question 31

How do you avoid layout thrashing when updating multiple elements?

A
Batch DOM reads and writes; modify elements together before forcing reflow
B
Force layout after every change
C
Use alert between updates
D
Query after each write
32

Question 32

Which pattern avoids repeated DOM queries inside loops?

A
const list = document.querySelector(".list"); forEach use list
B
Call document.querySelector repeatedly inside the loop
C
Use global selectors each time
D
Use innerHTML instead
33

Question 33

What is printed if querySelector finds no match?

javascript
const node = document.querySelector('.missing')
console.log(node)
A
null
B
undefined
C
Throws error
D
Empty NodeList
34

Question 34

How do you convert a NodeList to an array?

A
Array.from(document.querySelectorAll(".item"))
B
[...document.querySelector(".item")]
C
NodeList.toArray()
D
JSON.parse(NodeList)
35

Question 35

Which strategy prevents errors when manipulating optional elements?

A
Guard each query result or use optional chaining before calling properties
B
Assume elements exist
C
Wrap in try/catch always
D
Use innerHTML
36

Question 36

Why is storing DOM references in module scope useful?

A
It avoids repeated queries when the same element is needed in multiple functions
B
It prevents garbage collection
C
It hides elements automatically
D
It disables reflow
37

Question 37

What does document.querySelector("div.highlight span") select?

A
First span descendant inside a div with class highlight
B
All spans globally
C
Only direct child span
D
All highlighted elements
38

Question 38

Why might you store query results in const instead of let?

A
DOM references rarely need reassignment; const documents intent
B
const makes NodeList immutable
C
const is required
D
let is slower
39

Question 39

What best describes the DOM rendering flow regarding textContent updates?

A
Updating textContent schedules reflow/repaint; batch updates to minimize layout passes
B
textContent bypasses rendering
C
textContent updates require reload
D
textContent changes only on DOMContentLoaded
40

Question 40

What is a recommended best practice for DOM manipulation?

A
Use precise selectors, cache references, guard against null, and update text via textContent when HTML is not needed
B
Use innerHTML for all updates
C
Assume elements exist and skip checks
D
Store NodeList in global variables always

QUIZZES IN JavaScript