DOM Manipulation in JavaScript

JavaScript ~ 8 minutes

# Welcome to DOM Manipulation

Hello and welcome! In this tutorial, we will learn how JavaScript can change a web page. This skill is called DOM manipulation.

DOM means Document Object Model. When a browser opens your HTML file, it builds a tree of objects from it. Every heading, paragraph and button becomes one object in that tree. JavaScript can read these objects and change them. You can read more on MDN: Document Object Model.

What you will learn

  • How to select elements on the page
  • How to change text, styles and classes
  • How to create and remove elements
  • How to react to a button click

Do not worry if this is new for you. We will go slowly, one small step at a time.

Create a lesson folder
Code Copied to Clipboard

# Move into the folder

Good! The command above made a new folder called dom-lesson. This folder will keep all our lesson files in one place.

Now, please move inside this folder. We use the cd command for this. The letters cd mean change directory. After this step, every file we make will live in our lesson folder. A tidy folder helps you find your work later, so it is a very good habit to keep.

Enter the folder
Code Copied to Clipboard

# Make the HTML page

Now, please create a file named index.html inside the folder. Use any editor you like, such as VS Code or Notepad. Then create a second empty file named app.js in the same folder.

Files you need

  • index.html holds the page structure
  • app.js holds our JavaScript code

Look at the HTML on the next block. It has a heading with an id, a paragraph with a class, an empty list and a button. At the bottom, it loads our app.js file. We put the script tag at the end of the body, so the page is ready before the script runs.

index.html
Code Copied to Clipboard

Think of the DOM as a family tree

The DOM looks like a family tree. The document is the top parent. Inside it you find html, then head and body, and so on. Each item is called a node. When we change a node in JavaScript, the browser updates the page at once. The HTML file on your disk does not change. Only the page in the browser changes. If you refresh the page, your changes go away. This is normal, so please do not be afraid to experiment.

# Selecting elements

Before we can change something, we must find it. This is called selecting. JavaScript gives us a few easy ways to do it.

Common ways to select

  • getElementById('id') finds one element by its id
  • querySelector('.class') finds the first match for any CSS selector
  • querySelectorAll('li') finds all matches and returns a list

In the next block, we save three selections in variables. We also print some values with console.log. Open your browser, press F12, and look at the Console tab to see the output. Please try it now.

app.js - select elements
Code Copied to Clipboard
Always check that the element exists

If a selector finds nothing, querySelector gives you null. Then your next line will fail with an error like Cannot read properties of null. This is the most common beginner mistake. Please check three things when it happens:

Quick checklist

  1. Is the id or class spelled exactly the same in HTML and JavaScript?
  2. Is the script loaded after the element in the page?
  3. Did you use # for ids and . for classes in querySelector?

Remember, getElementById does not need the # sign, but querySelector does.

# Changing text and attributes

Now that we can select elements, let us change them. The property textContent sets plain text. The property innerHTML can also add HTML tags inside the element. For attributes, we use setAttribute.

In the next block, we change the heading text and the paragraph. We also give the paragraph a new data attribute and colour the heading. Notice that styles live in the style property, and CSS names use camelCase in JavaScript, for example backgroundColor. Save the file and refresh the browser to see the result.

Change content and style
Code Copied to Clipboard

# Working with classes

Changing styles one by one is slow. A cleaner way is to write CSS classes and switch them on and off with JavaScript. Every element has a classList object for this job.

Useful classList methods

  • add('name') adds a class
  • remove('name') removes a class
  • toggle('name') adds it if missing, removes it if present
  • contains('name') tells you true or false

The next block shows all four methods. This way, your CSS stays in the CSS file and your JavaScript stays simple. Many professional developers prefer this style.

Using classList
Code Copied to Clipboard

textContent or innerHTML?

Please prefer textContent when you only need text. It is faster and much safer. If you put text from a user into innerHTML, a bad user can add harmful scripts to your page. This attack is called XSS. Use innerHTML only for HTML that you wrote yourself. You can read more about it on MDN: innerHTML.

# Creating and removing elements

JavaScript can also build new elements from nothing. First we call createElement to make the element. Then we fill it with text. At last, we attach it to the page with appendChild.

In the next block, we create a list item and add it to the empty list. The new item appears on the page at once. To delete an element, you can call its remove() method. We left that line as a comment, so you can try it yourself. Removing and adding elements is how many modern web apps show new messages, tasks and products.

Create a new element
Code Copied to Clipboard

# Reacting to events

A web page feels alive when it reacts to the user. An event is something that happens, such as a click, a key press or a form submit. We listen for events with addEventListener.

This method takes two things. The first is the event name, like 'click'. The second is a function that runs when the event happens. In the next block, each click on our button raises a counter, updates the heading and adds a new list item. Please type this code carefully and click the button a few times. It is a small but real interactive feature!

Handle a button click
Code Copied to Clipboard

# Run a small local server

You can open index.html by double clicking it. But many developers like to use a small local server, because it behaves more like a real website. Python is installed on many computers, and it has a simple server built in.

Run the command in the next block from inside your lesson folder. Then open http://localhost:8000 in your browser. To stop the server later, press Ctrl and C together in the terminal.

Start the local server
Code Copied to Clipboard

# Try it yourself

Great work so far! Now, let us do a short practice. Try to add a second button that removes the last list item. You can use list.lastElementChild to find the last item, and then call remove() on it. If it does not work, check the Console for red error messages. They usually tell you the exact line with the problem. Making mistakes is a normal part of learning, so please be patient with yourself.

Wait for the page before you run code

Your script must run after the HTML elements exist. In this lesson, we put the script tag at the end of the body, so it works. If you place it in the head, add the defer attribute, like <script src='app.js' defer></script>. You can also wrap your code in a DOMContentLoaded listener. Without one of these, your selectors may return null, and your code will stop with an error.

# Summary and next steps

Well done! You finished the lesson. Let us review what we learned.

What we covered

  • The DOM is a tree of objects made from your HTML
  • We select elements with getElementById, querySelector and querySelectorAll
  • We change content with textContent and innerHTML
  • We switch styles using classList
  • We create and remove elements with createElement and remove
  • We react to users with addEventListener

Next steps

  • Build a small to-do list app
  • Learn about event delegation
  • Read the MDN DOM guide

Keep practising a little every day. You are doing very well!