Skip to content
Educora
Intermediate18 min11 / 27

The DOM and events

Control a page with JavaScript: find elements, change them, create new ones and respond to clicks and typing.

Check yourself
In this lesson you will learn
  • Explain what the DOM is
  • Find elements with querySelector and change their text, style and classes
  • Create new elements and add them to the page
  • Respond to clicks, typing and form submission with addEventListener

In an online shop you press “Add to cart”, and the number on the cart icon at the top goes up at once. The page doesn't reload — JavaScript simply changes one part of it. It does this through the DOM. Every example in this lesson is live: run it, click the buttons, change the code.

What is the DOM?

Definition
DOM (Document Object Model)

The tree of objects that the browser builds from an HTML page. Every tag becomes a node of the tree, and JavaScript can read, change and delete these nodes and add new ones.

Text
document
└── html
    ├── head
    │   └── title
    └── body
        ├── h1
        └── ul
            ├── li
            └── li
The DOM tree of a page with a heading and a two-item list. The root of the tree is the document object.

Finding and changing elements

document.querySelector() takes a CSS selector and returns the first matching element: '#greeting' searches by id, '.note' by class, 'h2' by tag. If you need all matching elements, use querySelectorAll(). On the element you found, textContent controls the text, style the styles and classList the CSS classes.

HTML
<style>
  .highlight { background: #ffe58a; }
</style>

<h2 id="greeting">Hello!</h2>
<p class="note">First note</p>
<p class="note">Second note</p>

<script>
  const greeting = document.querySelector('#greeting');
  greeting.textContent = 'Hello, Baku!';
  greeting.style.color = 'teal';

  const notes = document.querySelectorAll('.note');
  notes.forEach((note, i) => {
    note.textContent = `Note number ${i + 1}`;
    note.classList.add('highlight');
  });
</script>
Preview
Change the colour, write toggle instead of add and compare the result.

Creating new elements

document.createElement('li') creates a new element, but it isn't on the page yet. It appears once you add it inside an existing element with append(). To delete an element, call element.remove(). This way you can build a whole list from the data in an array:

HTML
<h3>Cities to visit</h3>
<ul id="cities"></ul>

<script>
  const cities = ['Baku', 'Ganja', 'Shaki', 'Lankaran'];
  const list = document.querySelector('#cities');

  for (const city of cities) {
    const item = document.createElement('li');
    item.textContent = city;
    list.append(item);
  }
</script>
Preview

Events

An event is something that happens on the page: a click, a key press, typing into a field, submitting a form. element.addEventListener('click', function) tells the browser: “When this element is clicked, call that function.” That function is called an event handler.

HTML
<button id="like">Like</button>
<span id="count">0</span> likes

<script>
  let likes = 0;
  const button = document.querySelector('#like');
  const count = document.querySelector('#count');

  button.addEventListener('click', () => {
    likes++;
    count.textContent = likes;
  });
</script>
Preview
Click the button a few times — the counter grows with every click.
EventWhen it happens
clickthe element is clicked
inputthe text in a field changes — on every character
submita form is submitted
keydowna key is pressed
mouseoverthe mouse moves over the element

A handler function receives an event object as its argument. Its preventDefault() method stops the browser's default behaviour — for example, reloading the page when a form is submitted. In the example below, the input event shows what you type right away, and submit displays a greeting.

HTML
<form id="form">
  <input id="name" placeholder="Your name">
  <button>Say hi</button>
</form>
<p id="preview">Start typing...</p>
<p id="result"></p>

<script>
  const input = document.querySelector('#name');
  const preview = document.querySelector('#preview');
  const result = document.querySelector('#result');

  input.addEventListener('input', () => {
    preview.textContent = `Typing: ${input.value}`;
  });

  document.querySelector('#form').addEventListener('submit', (event) => {
    event.preventDefault();
    result.textContent = `Hello, ${input.value || 'stranger'}!`;
  });
</script>
Preview

Mini project: a to-do list

Now let's put it all together: type a task, press “Add” — a new item appears in the list. Click an item and classList.toggle marks it as done; click again to unmark it.

HTML
<style>
  li { cursor: pointer; }
  .done { text-decoration: line-through; color: gray; }
</style>

<input id="task" placeholder="New task">
<button id="add">Add</button>
<ul id="list"></ul>

<script>
  const input = document.querySelector('#task');
  const list = document.querySelector('#list');

  document.querySelector('#add').addEventListener('click', () => {
    const text = input.value.trim();
    if (!text) return;
    const item = document.createElement('li');
    item.textContent = text;
    item.addEventListener('click', () => item.classList.toggle('done'));
    list.append(item);
    input.value = '';
  });
</script>
Preview
Improve it yourself: add a delete button to every item (item.remove()).
Exercise

In real projects the DOM only displays data, while the logic lives in plain functions. Write the logic of a to-do list without the DOM: toggle(index) flips the task's done value, and render() prints each task as [x] text or [ ] text, followed by a summary like Done: 1 of 3.

Exercise · JavaScript
const todos = [
  { text: 'Buy bread', done: false },
  { text: 'Learn the DOM', done: false },
  { text: 'Walk the dog', done: false },
];

function toggle(index) {
  // flip todos[index].done
}

function render() {
  // print [x] text or [ ] text for every task, then Done: N of M
}

toggle(0);
toggle(2);
toggle(2);
render();
▸ Expected output
[x] Buy bread
[ ] Learn the DOM
[ ] Walk the dog
Done: 1 of 3

Key points

  • The DOM is the tree of objects the browser builds from HTML; its root is document.
  • querySelector returns the first matching element, querySelectorAll returns all of them.
  • textContent, style and classList change an element's text, styles and classes.
  • createElement creates an element, append adds it to the page, remove deletes it.
  • addEventListener attaches a handler to an event; preventDefault() stops the browser's default behaviour.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What is the DOM?