← Back to course

The DOM

The DOM

Welcome back.

In the previous lesson, you learned objects.

Objects help JavaScript store structured data.

Very useful.

Very serious.

Very curly-brace friendly.

Today we move closer to real web development.

We are learning the DOM.

DOM means Document Object Model.

That sounds very official.

Almost like something written by a committee in a room with bad coffee.

But the idea is simple.

The DOM is how JavaScript sees your HTML page.

Thanks to the DOM, JavaScript can:

Without the DOM, JavaScript mostly lives in the console.

With the DOM, JavaScript can touch the page.

Carefully.

Usually.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, you will understand how JavaScript communicates with a web page.

This is a big step.

Before this, JavaScript was mostly talking to itself in the console.

Now it starts talking to the page.

Like a developer who finally leaves the terminal and sees sunlight.

Briefly.

Then returns to the terminal.

What Is the DOM?

The DOM is a representation of your HTML page.

When the browser loads HTML, it creates a structure that JavaScript can use.

Example HTML:

<h1>Hello</h1>
<p>Welcome to JavaScript.</p>

The browser turns this into something JavaScript can read and change.

JavaScript can then do things like:

document.querySelector("h1").textContent = "Hello from JavaScript!";

The page changes.

Magic?

No.

DOM.

Better than magic.

Because we can debug it.

Mostly.

HTML Becomes Objects

The word DOM means Document Object Model.

The important word here is object.

The browser treats elements as objects.

For example, this HTML element:

<h1 id="title">JavaScript</h1>

can be accessed in JavaScript:

const titleElement = document.getElementById("title");

Now titleElement is a JavaScript object that represents that HTML element.

You can read it.

Change it.

Style it.

Move it.

Make it suffer.

But please do not.

Use your power responsibly.

Create the Project

Create a folder for this lesson:

mkdir javascript-lesson7
cd javascript-lesson7
touch index.html
touch script.js

Your project should look like this:

javascript-lesson7/
  index.html
  script.js

Open the folder in your editor.

Today we will work directly with the web page.

The console is still useful.

But now the page will change too.

Finally, visible results.

The browser is preparing emotionally.

Write the HTML

Open index.html and add this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>The DOM</title>
</head>
<body>
  <h1 id="mainTitle">The DOM</h1>
  <p id="description">JavaScript can change this text.</p>

  <script src="script.js"></script>
</body>
</html>

Open the file in your browser.

Then open script.js.

We are ready to control the page.

Not the whole internet.

Just this page.

Let us stay humble.

Selecting an Element with getElementById

The method getElementById finds an element by its id.

Example:

const titleElement = document.getElementById("mainTitle");

console.log(titleElement);

Refresh the browser and open the console.

You should see the <h1> element.

This line:

document.getElementById("mainTitle")

means:

“Find the element with the id mainTitle.”

The id in HTML is:

<h1 id="mainTitle">The DOM</h1>

JavaScript finds it.

Stores it in a variable.

Now we can work with it.

Like a tiny web mechanic.

With fewer tools.

And more semicolons.

Changing Text with textContent

Now let us change the text.

Add this to script.js:

const titleElement = document.getElementById("mainTitle");

titleElement.textContent = "JavaScript Changed This Title";

Refresh the browser.

The title should change.

Original HTML:

<h1 id="mainTitle">The DOM</h1>

But JavaScript changes it to:

JavaScript Changed This Title

This is important.

The HTML file still contains the old text.

But the browser page shows the new text because JavaScript changed the DOM.

JavaScript did not rewrite your file.

It changed the page in the browser.

Like putting a hat on a statue.

The statue is still the same.

But now it looks different.

Selecting with querySelector

There is another very common way to select elements:

document.querySelector()

Example:

const descriptionElement = document.querySelector("#description");

descriptionElement.textContent = "The DOM is now under JavaScript control.";

The #description means:

“Find the element with id description.”

Just like CSS.

Because querySelector uses CSS selectors.

Examples:

document.querySelector("h1");
document.querySelector("#mainTitle");
document.querySelector(".card");

This makes querySelector very flexible.

If you know CSS selectors, you already know how to find elements.

Congratulations.

Your CSS knowledge has entered the JavaScript gym.

getElementById vs querySelector

Both can select elements.

Example with getElementById:

const title = document.getElementById("mainTitle");

Example with querySelector:

const title = document.querySelector("#mainTitle");

Both work.

Simple rule:

Use getElementById when you select by id.

Use querySelector when you want more flexibility.

For beginners, both are fine.

Do not start a religious war about this.

Programming already has enough drama.

Changing Styles with JavaScript

You can also change styles.

Example:

const titleElement = document.getElementById("mainTitle");

titleElement.style.color = "blue";
titleElement.style.fontSize = "48px";

Refresh the browser.

The title becomes blue and larger.

JavaScript can change CSS styles directly.

But be careful.

If you put too much styling inside JavaScript, the code can become messy.

Usually, CSS should handle styles.

JavaScript should add or remove classes.

That is cleaner.

Like using proper tools instead of fixing everything with tape.

Even if tape is sometimes powerful.

Changing Classes

Let us use classes instead of direct styles.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>The DOM</title>

  <style>
    .highlight {
      color: white;
      background-color: #2563eb;
      padding: 12px 18px;
      border-radius: 12px;
    }
  </style>
</head>
<body>
  <h1 id="mainTitle">The DOM</h1>
  <p id="description">JavaScript can change this text.</p>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const titleElement = document.getElementById("mainTitle");

titleElement.classList.add("highlight");

Refresh the browser.

The class is added.

The style appears.

This is a common pattern:

element.classList.add("class-name");

You can also remove a class:

element.classList.remove("highlight");

Or toggle a class:

element.classList.toggle("highlight");

toggle means:

Very useful.

Very elegant.

Almost suspicious.

Creating Elements

JavaScript can create new HTML elements.

Example:

const newParagraph = document.createElement("p");

newParagraph.textContent = "This paragraph was created by JavaScript.";

console.log(newParagraph);

This creates a paragraph.

But it does not appear on the page yet.

Why?

Because creating an element is not the same as adding it to the page.

You created it.

Now you need to attach it.

Like building a shelf and then remembering it is still on the floor.

Adding Elements to the Page

To add an element to the page, use appendChild.

Example:

const newParagraph = document.createElement("p");
newParagraph.textContent = "This paragraph was created by JavaScript.";

document.body.appendChild(newParagraph);

Refresh the browser.

Now the paragraph appears.

This line:

document.body.appendChild(newParagraph);

means:

“Add this new paragraph inside the body.”

Very useful.

This is how JavaScript can create dynamic content.

Tasks.

Messages.

Cards.

Products.

Random warnings.

The usual web development life.

Removing Elements

You can also remove elements.

Example:

const descriptionElement = document.getElementById("description");

descriptionElement.remove();

Refresh the browser.

The paragraph disappears.

JavaScript removed it from the DOM.

Again, the original HTML file is not changed.

Only the page in the browser changes.

The DOM is temporary.

Like your motivation after reading a long error message.

But we continue.

innerHTML

There is another property called innerHTML.

It allows you to insert HTML as a string.

Example:

const descriptionElement = document.getElementById("description");

descriptionElement.innerHTML = "<strong>This text is bold now.</strong>";

This works.

But be careful.

If you put user input inside innerHTML, it can be dangerous.

Why?

Because HTML can contain scripts.

And scripts can cause security problems.

For now, simple rule:

Use textContent for text.

Use innerHTML only when you really need HTML.

Do not feed random user input into innerHTML.

Security bugs are not cute.

They do not bring coffee.

Build a Message Panel

Now let us build a small message panel.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>The DOM</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 60px auto;
      padding: 0 24px;
      background-color: #f3f4f6;
      color: #111827;
    }

    .card {
      background-color: white;
      padding: 24px;
      border: 2px solid #e5e7eb;
      border-radius: 18px;
    }

    h1 {
      font-size: 42px;
    }

    p {
      font-size: 20px;
      line-height: 1.6;
    }

    button {
      background-color: #2563eb;
      color: white;
      border: none;
      padding: 14px 20px;
      border-radius: 999px;
      font-weight: 700;
      cursor: pointer;
      margin-right: 8px;
    }

    button:hover {
      background-color: #1d4ed8;
    }

    .message {
      margin-top: 20px;
      padding: 16px;
      border-radius: 14px;
      background-color: #eff6ff;
      border: 2px solid #bfdbfe;
    }

    .success {
      background-color: #ecfdf5;
      border-color: #bbf7d0;
      color: #166534;
    }

    .warning {
      background-color: #fffbeb;
      border-color: #fde68a;
      color: #92400e;
    }
  </style>
</head>
<body>
  <h1>The DOM</h1>

  <div class="card">
    <p id="message" class="message">Click a button to change this message.</p>

    <button id="successButton">Show Success</button>
    <button id="warningButton">Show Warning</button>
    <button id="clearButton">Clear</button>
  </div>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const messageElement = document.getElementById("message");
const successButton = document.getElementById("successButton");
const warningButton = document.getElementById("warningButton");
const clearButton = document.getElementById("clearButton");

function showSuccessMessage() {
  messageElement.textContent = "Success! The DOM has been updated.";
  messageElement.className = "message success";
}

function showWarningMessage() {
  messageElement.textContent = "Warning! JavaScript is touching the page.";
  messageElement.className = "message warning";
}

function clearMessage() {
  messageElement.textContent = "Click a button to change this message.";
  messageElement.className = "message";
}

successButton.addEventListener("click", showSuccessMessage);
warningButton.addEventListener("click", showWarningMessage);
clearButton.addEventListener("click", clearMessage);

Refresh the browser.

Click the buttons.

The message changes.

The style changes.

The page reacts.

This is the DOM in action.

JavaScript is no longer just talking.

It is doing.

Dangerous.

But beautiful.

How This Code Works

These lines find elements:

const messageElement = document.getElementById("message");
const successButton = document.getElementById("successButton");
const warningButton = document.getElementById("warningButton");
const clearButton = document.getElementById("clearButton");

This function shows a success message:

function showSuccessMessage() {
  messageElement.textContent = "Success! The DOM has been updated.";
  messageElement.className = "message success";
}

This function shows a warning message:

function showWarningMessage() {
  messageElement.textContent = "Warning! JavaScript is touching the page.";
  messageElement.className = "message warning";
}

This function resets the message:

function clearMessage() {
  messageElement.textContent = "Click a button to change this message.";
  messageElement.className = "message";
}

These lines connect buttons to functions:

successButton.addEventListener("click", showSuccessMessage);
warningButton.addEventListener("click", showWarningMessage);
clearButton.addEventListener("click", clearMessage);

This is a very important pattern:

User clicks.

Function runs.

DOM changes.

Page updates.

That is frontend development in one tiny sandwich.

Common Mistakes

Forgetting the # in querySelector

Wrong:

const title = document.querySelector("mainTitle");

Correct:

const title = document.querySelector("#mainTitle");

If you select by id with querySelector, use #.

Just like CSS.

Without #, JavaScript looks for an element named <mainTitle>.

Which probably does not exist.

Unless your HTML has become very creative.

Trying to Change an Element Before It Exists

If your script runs before the HTML is loaded, JavaScript may not find the element.

That is why we often put this near the end of the body:

<script src="script.js"></script>

After the HTML elements.

Good.

Simple.

Less drama.

Using textContent When You Want HTML

This:

element.textContent = "<strong>Hello</strong>";

shows the text exactly like this:

<strong>Hello</strong>

It does not create bold text.

For HTML, use:

element.innerHTML = "<strong>Hello</strong>";

But remember:

Use innerHTML carefully.

It is powerful.

And powerful things can create powerful headaches.

Using className and Removing All Classes by Accident

This:

messageElement.className = "success";

replaces all classes.

If the element had:

<p class="message"></p>

now it only has:

<p class="success"></p>

That might break your styling.

So we used:

messageElement.className = "message success";

Because we want to keep both classes.

Details matter.

CSS is watching.

Practice

Create a page with:

When the button is clicked:

Example HTML:

<h1 id="title">Old Title</h1>
<p id="text">Old text.</p>
<button id="changeButton">Change</button>

Example JavaScript:

const titleElement = document.getElementById("title");
const textElement = document.getElementById("text");
const changeButton = document.getElementById("changeButton");

function changeContent() {
  titleElement.textContent = "New Title";
  textElement.textContent = "The paragraph was changed by JavaScript.";
  textElement.classList.add("highlight");
}

changeButton.addEventListener("click", changeContent);

Run it.

Change it.

Break it.

Fix it.

The DOM becomes easier only when you practice.

It does not become easier by staring at it.

Unfortunately.

I tried.

Mini Challenge

Build a small notification box.

The page should have:

When the user clicks “Show Info”:

Information message shown.

When the user clicks “Show Error”:

Something went wrong.

When the user clicks “Reset”:

No message yet.

Use classes to change the style.

For example:

.info {
  background-color: #eff6ff;
}

.error {
  background-color: #fef2f2;
}

This challenge is very close to real work.

Websites constantly show messages.

Success.

Warnings.

Errors.

Forms.

Notifications.

Tiny boxes of emotional damage.

The DOM handles them all.

Summary

Today you learned:

This is a huge step.

The DOM is where JavaScript becomes visible.

Before the DOM, JavaScript is logic.

With the DOM, JavaScript becomes interaction.

Buttons.

Messages.

Cards.

Menus.

Forms.

Everything starts here.

The page is no longer just sitting there.

It is alive.

Slightly dramatic.

But alive.

Next Lesson

In the next lesson, we will learn events.

Events are how JavaScript reacts to users.

Clicks.

Typing.

Submitting forms.

Moving the mouse.

Pressing keys.

Basically, events are how the browser says:

“Something happened.”

And JavaScript says:

“I have a function for that.”