javascript · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Attributes are an element's settings, and code can change them.
An is extra information inside an opening tag, like id and class. A link's href says where it goes. getAttribute("href") reads it, and gives it a new value.
Some attributes are on-or-off switches, with matching true or false properties. hides an element and false brings it back. switches a button off, so clicks do nothing.
Use them to show a message only when it is needed, or to stop someone pressing Buy twice.
<a id="shop" href="https://example.com/old">Visit the shop</a>
<p id="sale" hidden>Sale now on!</p>
<button id="buy">Buy</button> const link = document.querySelector("#shop");
link.setAttribute("href", "https://example.com/new");
console.log(link.getAttribute("href"));
document.querySelector("#sale").hidden = false;
document.querySelector("#buy").disabled = true; Press run it to bring the page to life.
console
nothing logged yet
In HTML, hidden and disabled need no value. Being there switches them on.
guess first
Three clicks on the vote button. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<button id="vote">Vote for Biscuit</button>
<p id="votes">Votes: 0</p> const vote = document.querySelector("#vote");
let votes = 0;
vote.addEventListener("click", () => {
votes++;
document.querySelector("#votes").textContent = `Votes: ${votes}`;
vote.disabled = true;
});
your turn
Your turn. Reveal the riddle's hint.
Fill in the value that brings the hidden hint back. Then give the button a new label of your own. Press run and click Show hint.
the page your code works on
<p>What has keys but cannot open locks?</p>
<button id="show">Show hint</button>
<p id="hint" hidden>You play music on it.</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the hint is showingnot checked yet
- the button has a new labelnot checked yet
fix it
The cats link crashes instead of changing. Fix it!
the page your code works on
<a id="cats" href="https://example.com/dogs">See the cats</a>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the link goes to the cats pagenot checked yet
- The error comes from
setAttribute. Are its two arguments in the right order? - The attribute's name goes first and its new value second, like
setAttribute("id", "top"). - Swap the two strings on line 2 so "href" comes first, then press run.
nailed it
you switched parts of the page on and off. :D
setAttribute(name, value)changes an attribute,getAttributereads it.hidden = truehides an element, andfalseshows it.disabled = trueswitches a button off.
new words in your collection
- attribute
- setAttribute
- hidden
- disabled
This lesson isn’t saved. A free account remembers every lesson you finish.