CodeBlanks Logo Icon CodeBlanks

Summary - DOM basics

JavaScript course · Intermediate · Lesson 24/134

Update a profile card's information using querySelector and textContent.

Summary - DOM basics

In this group you learned what the DOM is, how to select elements and how to update text.

The document object is the root of the whole page; getElementById selects a single element by id, querySelector returns the first match for a CSS selector, and querySelectorAll returns all matches as a NodeList.

You can read and write a selected element's text with textContent. Let's combine these on a profile card.

Exercise Update the profile card

Select the element with id "user-name" using querySelector and assign it to userName; set userName.textContent to "Alex". In the same way select the element with id "user-role", assign it to userRole and set userRole.textContent to "Developer".

Show example solution
Select both elements with querySelector, then update them with textContent.
Example solution:
const userName = document.querySelector("#user-name");
userName.textContent = "Alex";
const userRole = document.querySelector("#user-role");
userRole.textContent = "Developer";

Exercise Mark all tasks as done

Select all elements with class "task" using querySelectorAll and assign them to tasks. Loop over each with for...of and set its textContent to "Done".

Show example solution
Select with querySelectorAll('.task'), loop with for (const task of tasks), inside write task.textContent = 'Done'.
Example solution:
const tasks = document.querySelectorAll(".task");
for (const task of tasks) {
  task.textContent = "Done";
}

Test yourself

  1. Which code selects the first element with class 'btn'?

    • getElementById(".btn")
    • querySelector(".btn")
    • querySelector("btn")
    • getElementById("btn")
    Show answer

    querySelector(".btn") — Correct! querySelector takes a class selector with the . sign.

  2. Read the text and update it

    const title = document.querySelector(".title");
    const old = title.____;
    title.textContent = "New";
    Show answer
    const title = document.querySelector(".title");
    const old = title.textContent;
    title.textContent = "New";

All lessons in Intermediate