Certainly! Here are some simple tasks with answers on the topic querySelector, querySelectorAll, and getElementById in JavaScript:
Task 1: Basic Selection with getElementById
Question:
Given the following HTML, write JavaScript code to select the element with id "title" and change its text content to "Hello World".
<h1 id="title">Original Text</h1>
Answer:
const title = document.getElementById('title');
title.textContent = 'Hello World';
Task 2: Selecting With querySelector
Question:
Given this HTML snippet, write JavaScript code to select the first paragraph with the class "intro" and change its color to red.
<p class="intro">Paragraph 1</p>
<p class="intro">Paragraph 2</p>
Answer:
const firstIntro = document.querySelector('.intro');
firstIntro.style.color = 'red';
Explanation:
querySelector selects only the first matching element.
Task 3: Selecting Multiple Elements With querySelectorAll
Question:
Given the following HTML, write JavaScript code to select all elements with the class "note" and log their text content to the console.
<div class="note">Note 1</div>
<div class="note">Note 2</div>
<div class="note">Note 3</div>
Answer:
const notes = document.querySelectorAll('.note');
notes.forEach(note => {
console.log(note.textContent);
});
Task 4: Difference between getElementById and querySelector
Question:
Given the HTML below, which method(s) will successfully select the <div> element?
<div id="container" class="box"></div>
If you want to select this element by its id, write the code using both getElementById and querySelector.
Answer:
// Using getElementById
const element1 = document.getElementById('container');
// Using querySelector by id selector
const element2 = document.querySelector('#container');
Both will select the same element.
Task 5: Using querySelector with complex selectors
Question:
Given this HTML, write JavaScript code using querySelector to select the <li> element inside the <ul> with id "menu" that has the class "active", and change its font weight to bold.
<ul id="menu">
<li>Home</li>
<li class="active">About</li>
<li>Contact</li>
</ul>
Answer:
const activeItem = document.querySelector('#menu li.active');
activeItem.style.fontWeight = 'bold';
Task 6: What happens if no elements are found?
Question:
Consider this code when no element matches the selector:
const el1 = document.querySelector('.does-not-exist');
const el2 = document.getElementById('missing-id');
console.log(el1);
console.log(el2);
What will be logged?
Answer:
null
null
Explanation:
- Both
querySelector and getElementById return null if no matching element is found.
If you want, I can also create more advanced tasks or explanations on event handling using these selectors!