Practice questions: DOM and events
DOM and events18 min readLesson 4 of 4
Answer each question first, then check the explanation. The code examples are self-contained and use created elements, so they can be pasted into a browser console on any page.
4.1 Q1 How do you select one element and all matching elements from the DOM?
Answer (English): document.querySelector(selector) returns the first matching element or null. document.querySelectorAll(selector) returns a NodeList of every match. Convert the NodeList to an array with spread when array methods are needed, and check for null before using a single selection.
Hinglish: document.querySelector pehla matching element ya null deta hai. document.querySelectorAll saare matches ki NodeList deta hai. Array methods chahiye to NodeList ko spread se array banao, aur single selection par null check karo.
4.2 Q2 What is the difference between textContent and innerHTML?
Answer (English): textContent reads or writes plain text and shows angle brackets as characters. innerHTML parses the string as HTML and can create elements, which also makes it unsafe for user or API data. Use textContent for data and innerHTML only for trusted template strings.
Hinglish: textContent plain text padhta ya likhta hai aur angle brackets ko characters ki tarah dikhata hai. innerHTML string ko HTML maan kar parse karta hai, isliye user ya API data ke liye unsafe hai. Data ke liye textContent, aur sirf trusted template ke liye innerHTML use karo.
4.3 Q3 How does an event listener receive the event, and what are target and currentTarget?
Answer (English): addEventListener passes the event object to the handler. event.target is the element where the event originated, while event.currentTarget is the element whose listener is currently running. They differ when an event bubbles from a child to an ancestor.
Hinglish: addEventListener handler ko event object deta hai. event.target woh element hai jahan event shuru hua, aur event.currentTarget woh element hai jiska listener abhi chal raha hai. Event bubble hokar parent tak pahunchta hai to dono alag hote hain.
4.4 Q4 Why is preventDefault needed on a form submit?
Answer (English): The browser's default submit action sends the form data and reloads the page, which destroys the current JavaScript state. Calling preventDefault stops that action so the handler can validate the fields and update the page in place. Server-side checks are still required for security.
Hinglish: Form ka default submit data bhejkar page reload karta hai, jisse JavaScript state khatam ho jata hai. preventDefault us action ko rokta hai taaki handler fields validate karke page ko wahin update kar sake. Security ke liye server-side check phir bhi zaroori hai.
4.5 Q5 What is event delegation and why use it for a list?
Answer (English): Delegation puts one listener on a parent and uses event.target with closest to find the item that was clicked. New items added later are handled without new listeners, and removed items leave no handlers behind. It also keeps the interaction logic in one place.
Hinglish: Delegation parent par ek listener lagata hai aur event.target ke saath closest se clicked item dhoondta hai. Baad mein aaye naye items bina naye listener ke handle ho jate hain, aur hataye gaye items ka listener bacha nahi rehta. Logic bhi ek jagah rehta hai.
4.6 Q6 How do you create and insert a new element?
Answer (English): Create it with document.createElement, set its text or attributes, then insert it with append, prepend, before or after. For many items, build them in a DocumentFragment and insert the fragment once to avoid repeated layout work.
Hinglish: document.createElement se element banao, uska text ya attributes set karo, phir append, prepend, before ya after se insert karo. Bahut items ke liye DocumentFragment mein banao aur ek baar insert karo, taaki layout baar-baar na chale.
4.7 Q7 Why does a task list keep its data in an array instead of reading the DOM?
Answer (English): The array is the single source of truth. Handlers change the array, and a render function rebuilds the visible list from it. Reading state back from the DOM is slow and ambiguous, especially after elements are removed or reordered, and it makes the data hard to save or test.
Hinglish: Array single source of truth hai. Handlers array badalte hain aur render function usse visible list dobara banata hai. DOM se state padhna slow aur ambiguous hota hai, khaaskar elements remove ya reorder hone ke baad, aur data ko save ya test karna mushkil ho jata hai.
4.8 Q8 How do you read the id of a clicked list item safely?
Answer (English): Store the id in a data attribute, then use event.target.closest("li") and read item.dataset.id. Compare it as a string or convert it with Number before matching against numeric ids. Return early when closest returns null, which happens when the click misses an item.
Hinglish: Id ko data attribute mein rakho, phir event.target.closest("li") se item lo aur item.dataset.id padho. Numeric ids se match karne se pehle string hi compare karo ya Number se convert karo. closest null de to turant return karo, kyunki tab click kisi item par nahi laga.
4.9 Q9 Why does a list re-render clear the old items first?
Answer (English): Clearing with list.innerHTML = "" removes the previous nodes before the new ones are built. Without the clear, every render appends another copy and the list grows on each update. Rebuilding is simple; patching individual nodes is an optimisation for very large lists.
Hinglish: list.innerHTML = "" purane nodes hata deta hai, phir naye items bante hain. Clear na karo to har render purani list par ek aur copy jod deta hai aur list badhti rehti hai. Rebuild karna simple hai; individual node patch karna bahut badi lists ke liye optimisation hai.
4.10 Q10 What should a form validate before saving a task?
Answer (English): Trim the title, reject an empty or too-short value, and enforce a maximum length. Show a message next to the field and keep the entered text so the user can correct it. The same rules should be repeated or enforced on the server when the data leaves the browser.
Hinglish: Title trim karo, khaali ya bahut chhota value reject karo, aur maximum length enforce karo. Message field ke paas dikhao aur enter kiya text waisa hi rakho taaki user sudhaar sake. Jab data browser se bahar jaye to wahi rules server par bhi lagao.
const button = document.createElement("button");
const output = document.createElement("p");
document.body.append(button, output);
let clicks = 0;
button.addEventListener("click", () => {
clicks += 1;
output.textContent = `Clicks: ${clicks}`;
});
button.click();
button.click();
console.log(output.textContent);Output
Clicks: 2
The five-question quiz for this module is separate. Take it without scrolling back. If an event or DOM answer feels uncertain, rebuild the small example in a blank page and log the values after each step.
