Practice Questions
1. What is the difference between an id and a class attribute in HTML? When would you use one over the other?
Solution
iduniquely identifies a single element on the page. Eachidshould only be used once.classlabels elements and can be shared by multiple elements.
<!-- id: unique identifier for one element -->
<div id="header">Site Header</div>
<!-- class: shared by multiple elements -->
<button class="btn">Save</button>
<button class="btn">Cancel</button>
Use id when you need to target one specific element. Use class when multiple elements share the same styling or behavior.
2. Write the CSS selectors to: (a) select all <p> elements, (b) select the element with id="main", and © select all elements with class="active".
Solution
/* (a) Select all <p> elements - use the tag name */
p {
color: blue;
}
/* (b) Select element with id="main" - prefix with # */
#main {
font-size: 18px;
}
/* (c) Select all elements with class="active" - prefix with . */
.active {
background-color: yellow;
}
These same selectors work with JavaScript’s querySelector and querySelectorAll.
3. What is the difference between getElementById and querySelector when selecting an element by its ID? Write both approaches for selecting an element with id="header".
Solution
Both can select an element by ID, but the syntax differs:
// getElementById - pass just the ID name (no #)
const header1 = document.getElementById("header");
// querySelector - use CSS selector syntax (with #)
const header2 = document.querySelector("#header");
Key differences:
getElementByIdonly selects by ID and is slightly fasterquerySelectoruses CSS selector syntax and can select by any selector (class, tag, attribute, etc.)getElementByIdreturnsnullif not found;querySelectoralso returnsnull
Both are valid. querySelector is more flexible since you can use the same method for all types of selections.
4. You have multiple buttons with the class btn on a page. Write code to select all of them and log each button’s text content.
Solution
const buttons = document.querySelectorAll(".btn");
buttons.forEach((button) => {
console.log(button.textContent);
});
querySelectorAll returns a NodeList of all matching elements. You can iterate over it with forEach to access each element individually.
5. You have a <p id="message"> element. Write code that changes its text to “Hello, World!” and adds a class called highlight to it.
Solution
const message = document.getElementById("message");
message.textContent = "Hello, World!";
message.classList.add("highlight");
textContentsets the text inside the elementclassList.add()adds a CSS class without affecting other classes the element may have
6. Explain why using textContent is safer than innerHTML when displaying user input on a page.
Solution
innerHTML parses content as HTML. If you insert untrusted user input, an attacker can inject elements or attributes, such as event handlers, and the browser will interpret them. That is how Cross-Site Scripting (XSS) happens:
const userInput = '<img src="x" onerror="stealData()">';
// Dangerous - the browser interprets this as HTML
element.innerHTML = userInput;
// Safe - displays as plain text
element.textContent = userInput;
textContent treats everything as plain text, so HTML tags are displayed literally rather than being parsed. Always use textContent for user-provided content.
7. Write code that adds a click event listener to a button with id="myBtn". When clicked, it should change the button’s text to “Clicked!”.
Solution
const button = document.getElementById("myBtn");
button.addEventListener("click", () => {
button.textContent = "Clicked!";
});
addEventListener takes two arguments: the event type (“click”) and a function to run when the event occurs. Inside the handler, we can modify the button using the button variable we already have.
8. A form reloads the page when submitted. Write the code pattern to handle the form submission with JavaScript instead, and explain why preventDefault() is needed.
Solution
const form = document.querySelector("#myForm");
form.addEventListener("submit", (event) => {
event.preventDefault();
// Handle the form data with JavaScript
const formData = new FormData(form);
const data = Object.fromEntries(formData);
console.log("Form data:", data);
});
preventDefault() stops the browser’s default behavior. For forms, the default is to send data to the server and reload the page. By calling preventDefault(), we stop the reload and handle the submission entirely with JavaScript (e.g., sending data via fetch).
9. Write a function createListItem(text) that creates a new <li> element with the given text content, adds a class "todo-item" to it, and returns the element. Then show how you would add this element to an existing <ul> with id="todo-list".
Solution
function createListItem(text) {
const li = document.createElement("li");
li.textContent = text;
li.classList.add("todo-item");
return li;
}
// Add to the list
const list = document.getElementById("todo-list");
const newItem = createListItem("Buy groceries");
list.appendChild(newItem);
Key points:
createElementcreates an element in memory (not yet on the page)- Configure the element (text, classes, etc.) before inserting
appendChildadds the element as the last child of the parent- You could also use
list.append(newItem)which works the same way for single elements
10. You have a button #toggle-btn and a div #menu. Write code that toggles a "hidden" class on the menu when the button is clicked. The button text should also update to show “Show Menu” when hidden and “Hide Menu” when visible.
Solution
const button = document.getElementById("toggle-btn");
const menu = document.getElementById("menu");
button.addEventListener("click", () => {
menu.classList.toggle("hidden");
const isHidden = menu.classList.contains("hidden");
button.textContent = isHidden ? "Show Menu" : "Hide Menu";
});
classList.toggle()adds the class if missing, removes it if presentclassList.contains()returnstrueorfalseto check current state- This pattern is common for show/hide functionality, dropdown menus, and accordions
11. In an event handler, what is the difference between using the variable you used to select the element versus using event.target? When might they refer to different elements?
Solution
The variable you used to select the element is the element you attached the listener to. event.target is the actual element that triggered the event, which may be a child element.
const container = document.getElementById("container");
container.addEventListener("click", (event) => {
console.log(container === event.target); // Not always true!
});
If container has child elements like buttons or links, clicking on a child means:
containeris the element with the listener (the parent)event.targetis the actual clicked element (the child)
<div id="container">
<button>Click me</button> <!-- clicking here: event.target is the button -->
</div>
This distinction matters when you want to know exactly what was clicked. It is also the basis for “event delegation,” where you attach one listener to a parent and check event.target to handle clicks on multiple children.