๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript DOM Intro

The DOM is the page held as objects that a script can read and change. A script finds an element object, then reads or sets its properties to work with the page.

Read before writing

The demo paragraph starts empty. The brackets make that empty text visible in the log line.

const demo = document.getElementById("demo");
console.log("Before: [" + demo.textContent + "]");

Set the text

Assigning to textContent puts new text inside the element. Reading it back proves the change landed.

const demo = document.getElementById("demo");
demo.textContent = "Hello from JavaScript";
console.log(demo.textContent);

Replace the text

A second assignment replaces the first text. Only the latest value stays in the element.

const demo = document.getElementById("demo");
demo.textContent = "First text";
demo.textContent = "Second text";
console.log(demo.textContent);

Example

const demo = document.getElementById("demo");
console.log("Before: [" + demo.textContent + "]");
demo.textContent = "Welcome to the page";
console.log(demo.textContent);

Key points

  • DOM stands for Document Object Model.
  • The document object represents the whole page.
  • getElementById finds the element with a given id.
  • The course intro lesson already used getElementById to write into the demo paragraph.
  • The textContent property holds the text inside an element.
  • Setting textContent replaces the text inside the element.

In this example, the script finds the demo paragraph by its id and reads its text while it is still empty. It then sets textContent to a welcome message. The final read-back shows the new text in place.

Note

innerHTML also sets content, but it parses tags, so text from strangers is a risk there and textContent is the safe habit.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does setting textContent on an element do?