Intermediate · 12 min
Read and update a page
Select elements and safely change their text.
Starting HTML
<h2 id="title">Study plan</h2>
<p id="message">Ready</p>
<ul id="items"></ul>Select an element
document.querySelector() returns the first matching element or null. A selector beginning with # looks for an ID. The HTML fixture is shown above the examples.
const message = document.querySelector("#message");
message.textContent = "Welcome";
console.log(message.textContent);Output
Welcome
Create an element
createElement() creates an element that is not yet on the page. Set its text, then append it. textContent treats input as text instead of interpreting HTML.
const item = document.createElement("li");
item.textContent = "Read";
document.querySelector("#items").appendChild(item);
console.log(document.querySelector("#items").children.length);Output
1
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Update the page message
Change the text of the element with ID message to "Welcome, Ada!". Run the code to see the page update.
Select #message instead of #title.
Page preview
Run your code, then try the controls below. Check solution resets the page and tries the actions described in the task.