JavaScript · Beginner level

Beginner level · Module 4: The DOM and Events · Lesson 1 of 3

Selecting and Changing Elements

Understand the DOM as a tree of elements, select elements with CSS selectors and change their text, classes and attributes.

In this lesson you will

  • Select elements with querySelector and querySelectorAll
  • Change text, classes and attributes safely

Key concepts

DOM treequerySelectortextContent vs innerHTMLclassList

The lesson

The browser turns HTML into a tree of objects called the DOM (Document Object Model). JavaScript can read and change this tree, and the page updates immediately.

document.querySelector("#total") returns the first element matching a CSS selector; querySelectorAll returns all matches. Use IDs or specific classes so your selections do not break when the design changes.

Set text with element.textContent = value, which treats the value as plain text. innerHTML parses HTML, so inserting user-provided text with it can run malicious code (cross-site scripting). Change styles by adding or removing CSS classes with classList.add, remove and toggle rather than setting styles directly.

Step by step

  1. Select a heading by ID and change its text.
  2. Select all list items and print how many there are.
  3. Highlight an element by adding a CSS class.
  4. Show the difference between textContent and innerHTML with a tag in the text.

Practice activity

Write a script that fills a page's total, date and status elements from variables, highlighting the status in red when payment is overdue.

Expected result: The page shows the values and the overdue style appears only when the condition is true.

Check your understanding

  1. Why prefer textContent over innerHTML for user text?

    Show answer

    textContent treats it as plain text, so it cannot inject HTML or scripts.

  2. How should JavaScript change an element's appearance?

    Show answer

    By adding or removing CSS classes with classList.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.