๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Full-Stack Web Development Bootcamp Module 2 ยท Lesson 4 of 15

0% Exit to course

Module 2 ยท JavaScript in the browser Lesson 4 of 15

The DOM and events

Learning objective

The DOM is the page as objects. Events are how the browser tells your code that a user did something.

The concept

The DOM is the browser's live model of your HTML: every tag becomes an object you can read and change with JavaScript. document.querySelector('.card') finds one element, and changing its textContent, classList or style updates the page immediately without a reload.

Events are how the user talks to you. addEventListener('click', handler) runs your function when something happens, and the same pattern covers submit, input, keydown and scroll. Keep the JS in its own file and use defer when you load it, so the HTML is parsed before your script looks for elements.

JavaScript
// Build a small list, then attach ONE listener to the list itself.
const list = document.createElement('ul');
['Python', 'SQL', 'React'].forEach((name) => {
  const li = document.createElement('li');
  li.textContent = name;
  list.appendChild(li);
});

list.addEventListener('click', (e) => {
  if (e.target.tagName === 'LI') console.log('You clicked ' + e.target.textContent);
});

document.body.appendChild(list);
console.log('Click a skill in the list above โ€” the log below shows which one.');

Common mistakes

The mistake is attaching one listener per row inside a loop that re-renders โ€” 500 rows, 500 listeners, and the removed ones leak. Attach ONE listener to the container and read event.target to see what was clicked. That is event delegation, and it is the answer interviewers want.

Worked example

document.getElementById("apply").addEventListener("click", fn) is the shape of every interactive feature you will ever write.

Your practice task

Build a counter and a show/hide panel, each in vanilla JavaScript with no library.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

The DOM is the browser's live model of your HTML: every tag becomes an object you can read and change with JavaScript.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.

Next recommended course Data Analytics with SQL & Excel