DOM manipulation basics
Computer Science · JavaScript
Question 1 of 10
0This is the HTML body of a page: <ul> <li class="item">apple</li> <li class="item">apple</li> <li class="item">plum</li> <li class="item">pear</li> <li class="plain">lime</li> </ul> <p class="item">note</p> How many elements does document.querySelectorAll(".item") return?
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
DOM manipulation basics explained
The Document Object Model, or DOM, is the browser's tree of objects that represents a web page. JavaScript reads and changes that tree to update what the user sees, without reloading the page.
Each element, such as a heading, paragraph or list item, is a node in the tree. document.querySelector takes a CSS selector such as "h1" or "#save" and returns the first match, or null if there is none. document.querySelectorAll returns all matches.
const title = document.querySelector("h1");
title.textContent = "Hello";
const item = document.createElement("li");
item.textContent = "Milk";
document.querySelector("ul").appendChild(item);
textContent treats its value as plain text. innerHTML parses a string as HTML, which is dangerous with user-supplied content because it can inject scripts. Classes are changed with classList.add and classList.remove. These methods exist only in a browser, not in Node.js.
Worked example
A shopping list has a ul with two li items. The code above adds a third, so document.querySelectorAll("li").length goes from 2 to 3. If the script runs before the page is parsed, querySelector returns null, and calling textContent on null throws a TypeError.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
This is the HTML body of a page:
How many elements does document.querySelectorAll("li.item") return?
Medium
Here is the page.
57 56
After this script runs, what is the textContent of #out? const total = Number(document.getElementById("a").textContent) + Number(document.getElementById("b").textContent); document.getElementById("out").textContent = total;
Hard
This is the HTML body of a page:
How many elements does document.querySelectorAll(".box > .hit") return?