javascript · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
takes an element away, clears all.
Every element has a remove() method. Call it, and the element leaves the page along with everything inside it.
A neat trick: make a Done button along with each new item. Its listener is written inside the loop, so it remembers its own item and removes exactly that one, however many items there are.
To empty a parent completely, call replaceChildren() with nothing in the brackets. Every child goes in one step, which is handy before drawing a list again.
<ul id="jobs"></ul> const jobs = document.querySelector("#jobs");
for (const job of ["Wash up", "Hoover", "Empty the bins"]) {
const item = document.createElement("li");
const done = document.createElement("button");
item.textContent = job;
done.textContent = "Done";
done.addEventListener("click", () => { item.remove(); });
item.append(done);
jobs.append(item);
} Press run it to bring the page to life.
console
nothing logged yet
Click a Done button and only its own job disappears.
guess first
Clear the basket, then add. What is left?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<ul id="basket">
<li>Pears</li>
<li>Plums</li>
</ul> const basket = document.querySelector("#basket");
basket.replaceChildren();
const fruit = document.createElement("li");
fruit.textContent = "Peaches";
basket.append(fruit);
your turn
Your turn. Pop the balloons.
Fill in the method that takes an element off the page. Press run, then click a balloon to pop it.
the page your code works on
<p class="balloon">Red balloon</p>
<p class="balloon">Blue balloon</p>
<p class="balloon">Green balloon</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- two clicks pop two balloonsnot checked yet
fix it
The Clear button does nothing. Fix it!
the page your code works on
<ul id="board">
<li>Buy stamps</li>
<li>Ring Gran</li>
</ul>
<button id="clear">Clear the board</button>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- a click empties the boardnot checked yet
- The console says Board cleared, so the listener runs. But does line 3 do anything?
- A method only runs when you call it, and calling needs something after its name.
- Add brackets on line 3, so it reads board.replaceChildren(); then press run.
nailed it
you can tidy the page away. :D
element.remove()takes one element off the page.replaceChildren()with empty brackets clears every child.- A button made with an item can remove its own item.
new words in your collection
- remove
- replaceChildren
This lesson isn’t saved. A free account remembers every lesson you finish.