Popular Searches
Popular Course Categories
Popular Courses

DOM selection & events

DOM selection & events

28 mins DOM & Browser APIs

DOM selection & events in React JS

Course: React JS Training

Topic: DOM selection & events

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why the DOM matters for every web developer

HTML gives a page its structure, CSS gives it its appearance, and JavaScript is what makes it respond to the person using it. The bridge between your JavaScript code and the visible page is the DOM (Document Object Model). Two skills sit at the heart of that bridge: selection, which means finding the exact element you want to work with, and events, which means reacting when the user clicks, types or submits something.

Nearly every interactive behaviour you have seen on the web — a menu that opens, a form that checks your email, a counter that updates as you type — follows the same three-step pattern: select an element, listen for an event, update the page. Master that pattern in plain JavaScript and you can build interactivity from scratch.

This also prepares you for React. React automates much of the updating for you, but it does its work on the very same DOM you will manipulate by hand here. When you later meet React's components and its event system, they will make far more sense because you already know what the browser is doing underneath. Plain JavaScript questions, including tricky ones hidden inside simple-looking code, are also standard material in frontend interviews.

2. What is the DOM in simple words

When the browser loads an HTML file, it does not keep the file as plain text. It reads every tag and builds a live model of the page in memory: a tree of objects, one object for each element. This model is the Document Object Model, or DOM.

The DOM is the browser's live, in-memory map of your page — one object per tag — which JavaScript can search, read and change at any moment.

Three things make this model special:

  • It is a tree. Every element sits in a family-like hierarchy: a parent above it, children below it, siblings beside it.
  • It is live. When JavaScript changes a node, the browser repaints the screen immediately. There is no "save and refresh" step.
  • It is a two-way door. The browser builds the DOM from your HTML, and JavaScript can add, remove or rearrange nodes, which changes what the page shows.

A helpful analogy: the HTML file is the architect's drawing, and the DOM is the finished building. JavaScript can walk through its rooms (select elements), rearrange the furniture (change content and styles) and install doorbells that ring when someone presses them (event listeners).

3. Key terms you will meet in this module

These words appear constantly in documentation and tutorials, so fix their meanings now:

  • Node — any single item in the DOM tree. Elements, pieces of text and comments are all nodes.
  • Element — a node that represents a tag, such as a <p> or <button>. Most daily work targets elements.
  • Selection — searching the tree for the node or nodes you want, and receiving a reference to them.
  • Reference — the value a selection method returns: not a copy, but a handle pointing at the live object in the tree.
  • Event — a signal from the browser that something happened, such as click, keydown or submit.
  • Event listener (also called a handler) — a function you register so it runs whenever a given event happens on a given element.
  • Event object — an object the browser creates for each event, carrying details such as which element was clicked.
  • Event target — the element on which the event originally happened.
  • Event bubbling — the way an event, after firing on its target, travels upward through the parent elements.
  • Event delegation — a technique where one listener on a parent handles events for many children, using bubbling.

4. The DOM tree: how HTML becomes objects

Take this small page:

<!DOCTYPE html>
<html>
  <body>
    <h1 id="title">Welcome</h1>
    <ul id="menu">
      <li>Home</li>
      <li>Courses</li>
    </ul>
  </body>
</html>

The browser turns it into a tree like this:

  • html
    • body
      • h1#title — with the text "Welcome" inside it
      • ul#menu
        • li — "Home"
        • li — "Courses"

The family vocabulary becomes concrete here: body is the parent of the h1 and the ul; the two li elements are children of the ul and siblings of each other. The tree matters because both of this module's skills travel along it: selectors such as ul li describe positions in the tree, and events such as a click move through it from child to parent.

5. Selecting elements: methods and how selection works

The modern way: querySelector and querySelectorAll

The two methods you will use almost every day accept any CSS selector — the same syntax you already know from styling:

const title   = document.querySelector('#title');        // by id
const button  = document.querySelector('.btn-primary');   // by class
const firstLi = document.querySelector('ul li');          // first li inside any ul
const allLis  = document.querySelectorAll('li');          // every li on the page
  • document.querySelector(selector) returns the first matching element, or null if nothing matches.
  • document.querySelectorAll(selector) returns all matches as a NodeList, which you can loop over with forEach. If nothing matches, you get an empty list rather than null.

Classic methods still worth recognising

Older codebases use these, so you should be able to read them:

document.getElementById('title');          // one element, by id
document.getElementsByClassName('btn');     // many elements, by class
document.getElementsByTagName('li');       // many elements, by tag name

One subtle difference matters in practice: the two "Elements" methods return a live HTMLCollection that updates itself when the page changes, while querySelectorAll returns a static snapshot taken at the moment you called it.

Choosing between them

MethodYou passReturnsGood to know
querySelectorany CSS selectorfirst match, or nullmost flexible; one method for every case
querySelectorAllany CSS selectorstatic NodeListsupports forEach; empty list if no match
getElementByIdan id stringthe element, or nullclear and direct when an id exists
getElementsByClassNamea class stringlive HTMLCollectionauto-updates as the page changes
getElementsByTagNamea tag namelive HTMLCollectionauto-updates as the page changes

How selection works, step by step

  1. The browser parses your HTML and builds the DOM tree.
  2. Your script runs. It must run after the elements exist, so either place the <script> just before the closing </body> tag or add the defer attribute to it.
  3. You call a selection method with a selector string.
  4. The browser walks the tree and returns a reference to the first match, or a list of matches.
  5. If nothing matched, querySelector gives you null. Check for this before using the result, or the next line will throw an error.
  6. The reference points at the live object, so any change you make shows on the page at once.

6. Reading and changing what you selected

Selection is only useful because the reference lets you read and modify the element. These are the members you will reach for first:

const title = document.querySelector('#title');

title.textContent = 'DOM basics';             // replace the text, as plain text
title.classList.add('highlight');             // add a CSS class
title.classList.toggle('hidden');             // add if absent, remove if present
title.style.color = 'teal';                   // one inline style
title.setAttribute('data-page', 'home');      // set any attribute

console.log(title.textContent);               // read the current text back

A safety note worth learning early: textContent treats whatever you assign as plain text, while innerHTML parses the string as HTML. Never build HTML out of user input and hand it to innerHTML — that is the classic doorway for script-injection attacks. For text, textContent is both safer and usually what you mean.

7. What an event really is

An event is a signal the browser fires when something happens: the user clicks, presses a key, submits a form, resizes the window, or the page finishes loading. Your code does not sit in a loop watching for these things. Instead, you register a listener, and the browser calls your function at the right moment. This style — "call me when X happens" — is called event-driven programming, and it is how all browser JavaScript works.

Events come in families. The ones you will use most often:

FamilyCommon eventsFires when
Mouseclick, dblclick, mouseover, mouseoutthe pointer acts on an element
Keyboardkeydown, keyupa key is pressed or released
Form and inputsubmit, focus, blur, change, inputform fields are used or values change
Document and windowDOMContentLoaded, load, resize, scrollpage-level moments occur

One distinction beginners find useful: input fires on every keystroke inside a field, while change fires when the value is "committed" — typically when the field loses focus. For a live character counter you want input; for validating a finished entry, change often fits better.

8. addEventListener: the syntax and structure

The standard way to attach a listener is the addEventListener method, available on every element:

element.addEventListener('eventType', handlerFunction);

// a real example
const button = document.querySelector('#save');

button.addEventListener('click', () => {
  console.log('Saved!');
});

Reading the parts:

  • Event type — the event name as a string: 'click', 'input', 'submit'. There is no "on" in the string; that prefix belongs to the old inline style.
  • Handler function — the function to run. An arrow function is the popular modern choice; a regular function works the same way here.
  • Repetition — the handler runs every time the event happens, not just once. You can attach several listeners to the same element, even for the same event type.

Removing a listener

removeEventListener exists, but it only works if you pass the same function reference you added. An inline arrow function cannot be removed later, because the browser has no way to know which function you mean:

function onClick() {
  console.log('Clicked');
}

button.addEventListener('click', onClick);
button.removeEventListener('click', onClick);   // works: same reference

For a listener that should run a single time and then disappear, there is a cleaner option:

button.addEventListener('click', handler, { once: true });

9. How event handling works, step by step

A surprising amount happens behind a single click. Here is the full journey:

  1. The user performs an action — say, clicking a button.
  2. The browser creates an event object describing what happened: the type, the pointer position, the element involved.
  3. The browser identifies the target: the deepest element the action landed on.
  4. The event travels through the tree: first down from the document to the target (the capturing phase), then it fires on the target, then it moves up through its ancestors (the bubbling phase).
  5. As it passes each node, the browser runs any listeners registered there for that event type, in order.
  6. If a listener calls event.preventDefault(), the browser's built-in default action for that event — such as a form submit reloading the page — is cancelled.
  7. With all listeners done, the browser carries out the default action, unless it was prevented.

You do not need to memorise the capturing phase yet. Bubbling is the phase you will use deliberately, and a later section shows how.

10. The event object: what the browser hands your function

Every handler receives the event object as its argument. It answers the two questions you will almost always ask: what happened and where?

button.addEventListener('click', (event) => {
  console.log(event.type);        // "click"
  console.log(event.target);      // the element that was actually clicked
});
MemberWhat it tells you
event.typethe event name, such as "click" or "submit"
event.targetthe element where the event originated
event.currentTargetthe element the listener is attached to (the same as target in simple cases)
event.keyfor keyboard events, which key was pressed, such as "Enter"
event.preventDefault()cancels the browser's default action
event.stopPropagation()stops the event from bubbling further up the tree

The most used method by far is preventDefault(). A form submit would normally send the data and reload the page, destroying your JavaScript's chance to react. Intercepting it looks like this:

const form = document.querySelector('#signup');

form.addEventListener('submit', (event) => {
  event.preventDefault();     // the page will not reload
  console.log('Now we handle the form ourselves');
});

11. Worked examples: from a first click to a realistic feature

Example 1: your first click handler

<h1 id="title">Hello</h1>
<button id="changeBtn">Change the title</button>

<script>
  const button = document.querySelector('#changeBtn');
  const title  = document.querySelector('#title');

  button.addEventListener('click', () => {
    title.textContent = 'You clicked the button!';
  });
</script>

Step by step: select the button and the heading, register a click listener on the button, and inside the handler change the heading's text. The moment the user clicks, the browser calls your function and the heading updates instantly — the full select, listen, update pattern in a few lines.

Example 2: a live character counter

<input id="message" maxlength="50">
<p><span id="count">0</span>/50 characters</p>

<script>
  const input = document.querySelector('#message');
  const count = document.querySelector('#count');

  input.addEventListener('input', () => {
    count.textContent = input.value.length;
  });
</script>

Because we listen to input rather than change, the counter updates on every keystroke, exactly like the counters on real signup forms. Notice that we read the current value from input.value, a property of the element object itself.

Example 3: intercepting a form with simple validation

<form id="signup">
  <input id="email" type="email" placeholder="[email protected]">
  <button type="submit">Sign up</button>
  <p id="error"></p>
</form>

<script>
  const form  = document.querySelector('#signup');
  const email = document.querySelector('#email');
  const error = document.querySelector('#error');

  form.addEventListener('submit', (event) => {
    event.preventDefault();                  // stop the page reload

    const value = email.value.trim();

    if (!value.includes('@')) {
      error.textContent = 'Please enter a valid email address.';
      return;
    }

    error.textContent = '';
    console.log('Ready to send:', value);
  });
</script>

This is the shape of nearly all client-side form handling: prevent the default submit, read the field values, validate, and either show a message or proceed. Note that the listener sits on the form, not the button — the submit event belongs to the form, and it fires even if the user presses Enter inside the field.

12. Bubbling, capturing and event delegation

Click one of the list items below and you have technically clicked more than the item: the click also happened "inside" the ul, the body and the html element. That is bubbling: after firing on the target, the event climbs the tree, visiting each ancestor, and any of those ancestors may have a listener that will run.

Instead of a problem, this is a tool. Event delegation means attaching one listener to a parent and letting it handle events for all its children, checking event.target to see which child was actually hit:

<ul id="tasks">
  <li>Learn selectors</li>
  <li>Learn events</li>
  <li>Build a small project</li>
</ul>

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

  list.addEventListener('click', (event) => {
    if (event.target.tagName === 'LI') {
      event.target.classList.toggle('done');
    }
  });
</script>

Two reasons this pattern is loved:

  • Fewer listeners. One listener serves the whole list, instead of one per item.
  • It survives change. If JavaScript later adds a new <li> to the list, clicks on it are handled automatically — no new listener needed, because the listener lives on the parent.

The opposite direction — the event travelling down the tree before reaching the target — is the capturing phase. It is rarely needed in day-to-day work; it is enough for now to know that it exists and happens before bubbling. If you ever need to stop an event from climbing further, event.stopPropagation() does exactly that.

13. Common mistakes and good habits

Most beginner bugs in this module come from a handful of repeat offenders. Learn them now and you will debug far less:

Common mistakeWhat happensBetter habit
Running the script before the elements existquerySelector returns null and the next line throwsput the <script> at the end of <body>, or use the defer attribute
Using the selected element without a check"cannot read properties of null" errorscheck if (element) before using it, especially when markup may change
Writing addEventListener('onClick', ...)the listener never firesthe event name has no "on": it is 'click', 'input', 'submit'
Attaching handlers with inline onclick attributes in HTMLlogic is scattered, and only one handler per event is possibleattach listeners from JavaScript with addEventListener
Inserting user input with innerHTMLopens the door to script-injection attacksuse textContent for text
Forgetting event.preventDefault() on submitthe page reloads and your work vanishesprevent the default as the first thing in a submit handler
Looping over children to add one listener eachmany listeners, and new children are not covereddelegate: one listener on the parent, dispatch via event.target

One habit ties all of these together: keep the three-step rhythm in mind for every feature you build — select, listen, update. If something does not work, ask which of the three steps failed: did the selection find nothing, did the listener never fire, or did the update target the wrong element? Almost every DOM bug is one of those three.

14. Advanced selection: moving around the tree and creating elements

A selection gives you a live reference, and from any element you can reach its neighbours without running a new search. These traversal properties are read like ordinary values:

const item = document.querySelector('.item');

item.parentElement;              // the element one level up
item.children;                   // the elements directly inside it
item.nextElementSibling;         // the next element at the same level
item.previousElementSibling;     // the previous one

Two selector-based helpers are extremely useful in event handlers. closest(selector) starts at an element and walks upward until it finds an ancestor matching the selector, while matches(selector) simply answers whether an element would match a given selector:

// from a deeply nested element, find the list item it belongs to
const row = event.target.closest('li');

// ask a yes/no question about an element
if (button.matches('.primary')) {
  console.log('This is a primary button');
}

Selection is not only about finding existing elements. You can also build new nodes in memory and attach them to the page:

const li = document.createElement('li');   // create, still invisible
li.textContent = 'New task';
li.classList.add('task');

const list = document.querySelector('#tasks');
list.append(li);                            // now it appears on the page

// later, remove an element entirely
li.remove();

A node created with createElement is detached: it exists in memory but is not part of the visible tree until you append it somewhere. This two-step style — build first, attach once — is the efficient way to add content, and you will see it used in the project below.

15. Keyboard and input events in real features

Clicks are only half the story. Keyboard events let you react to keys, and the event object's key property tells you which one was pressed. A classic use is submitting a form field with the Enter key:

const input = document.querySelector('#taskInput');

input.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    addTask(input.value);
    input.value = '';
  }
});

Input events also power small quality-of-life features. A common one is restricting a quantity field to digits, by cleaning the value on every keystroke:

const qty = document.querySelector('#quantity');

qty.addEventListener('input', () => {
  qty.value = qty.value.replace(/[^0-9]/g, '');
});

Here the handler reads the field's current text, removes every character that is not a digit, and writes the cleaned value back. The user never sees the invalid characters linger — the field corrects itself as they type.

16. A realistic pattern: tabbed content with delegation

Tab panels appear on almost every product page. The clean implementation combines three ideas from this module: data-* attributes, delegation, and toggling classes. data-* attributes let you attach your own named information to any element, and JavaScript reads them through the dataset property:

<div class="tabs">
  <button data-tab="one">Details</button>
  <button data-tab="two">Reviews</button>
</div>
<p id="panel-one">Course details go here.</p>
<p id="panel-two" class="hidden">Student reviews go here.</p>

<script>
  const tabs = document.querySelector('.tabs');

  tabs.addEventListener('click', (event) => {
    const button = event.target.closest('button');
    if (!button) return;

    document.querySelectorAll('.tabs button')
      .forEach(b => b.classList.remove('active'));
    button.classList.add('active');

    document.querySelectorAll('#panel-one, #panel-two')
      .forEach(p => p.classList.add('hidden'));
    document.querySelector('#panel-' + button.dataset.tab)
      .classList.remove('hidden');
  });
</script>

One listener on the container handles every tab button, present or future. The data-tab value is joined onto #panel- to build the selector for the panel to show. Notice the styling rule in spirit here: JavaScript only toggles classes such as hidden and active; what those classes look like stays in CSS.

17. More common mistakes, each with the correct way

Trusting event.target when the element has children

If a list item contains a <span>, clicking the text makes the span the target, not the item. Also remember that tagName is reported in uppercase:

// Wrong: misses clicks on inner elements, and lowercase never matches
if (event.target.tagName === 'li') { ... }

// Right: climb to the item no matter what was clicked inside it
const li = event.target.closest('li');
if (li) {
  li.classList.toggle('done');
}

Re-attaching listeners after every update

A frequent bug: code that rebuilds a list also adds listeners again, so after three rebuilds one click runs the handler three times. The correct way is to bind once on a stable parent and delegate, as the tab example does — new children are covered automatically and no listener is ever duplicated.

Building lists with innerHTML += in a loop

// Wrong: re-parses the whole list on every pass, and any listeners
// inside it are destroyed and silently recreated
for (const name of names) {
  list.innerHTML += '<li>' + name + '</li>';
}

// Right: create elements and append them
for (const name of names) {
  const li = document.createElement('li');
  li.textContent = name;
  list.append(li);
}

Each += on innerHTML makes the browser re-read the entire HTML of that container. Besides being slow, it wipes out any event listeners attached to the old children.

Treating a NodeList as an array

const items = document.querySelectorAll('.item');

items.forEach(item => console.log(item));   // works: NodeList has forEach
items.map(item => item);                    // error: NodeList has no map

const arr = [...items];                     // convert when you need map/filter

A NodeList from querySelectorAll supports forEach but not the full array toolbox. Spread it into a real array when you need more.

Mixing handler styles

An element can have an onclick property or inline onclick attributes in the HTML or any number of addEventListener calls. The property and the attribute overwrite each other, and inline handlers scatter your logic into the markup. Pick one style — addEventListener — and use it everywhere.

18. Best practices for DOM work

  • Select once, store the reference. Keep results in const variables with clear names instead of searching the same tree repeatedly.
  • Keep handlers small. A handler should read the input, call a named function, and little else. Named functions are also easier to test and to remove later.
  • Delegate on stable parents whenever children are added or removed dynamically.
  • Use textContent for anything a user typed. Reserve innerHTML for HTML you wrote yourself.
  • Carry meaning in data-* attributes rather than inventing one id per element; dataset makes them easy to read.
  • Toggle classes, do not paint styles. Let CSS own appearance; JavaScript only adds and removes class names.
  • Guard against null after every selection, especially in shared code where the markup may change under you.
  • Load scripts at the right time: at the end of <body> or with the defer attribute, so the elements already exist.

19. Practical project: an interactive task list

This small project combines everything on the page: selection, creation, form handling, keyboard-friendly input, delegation and counters. It is also a classic portfolio starter.

Step 1: write the markup

<form id="taskForm">
  <input id="taskInput" placeholder="What needs doing?">
  <button type="submit">Add task</button>
</form>
<ul id="taskList"></ul>
<p><span id="pending">0</span> tasks pending</p>

Step 2: select the elements once

const form    = document.querySelector('#taskForm');
const input   = document.querySelector('#taskInput');
const list    = document.querySelector('#taskList');
const pending = document.querySelector('#pending');

Step 3: write the helper functions

function updateCount() {
  const total = list.querySelectorAll('li').length;
  const done  = list.querySelectorAll('li.done').length;
  pending.textContent = total - done;
}

function addTask(text) {
  const li = document.createElement('li');

  const label = document.createElement('span');
  label.textContent = text;

  const doneBtn = document.createElement('button');
  doneBtn.textContent = 'Done';
  doneBtn.dataset.action = 'toggle';

  const delBtn = document.createElement('button');
  delBtn.textContent = 'Delete';
  delBtn.dataset.action = 'delete';

  li.append(label, doneBtn, delBtn);
  list.append(li);
}

addTask builds the row piece by piece — text first, then two buttons carrying a data-action — and attaches the finished row in one move. Note that textContent is used for the user's task text, so any characters the user types are treated as plain text.

Step 4: handle the form submit

form.addEventListener('submit', (event) => {
  event.preventDefault();
  const text = input.value.trim();
  if (text === '') return;

  addTask(text);
  input.value = '';
  input.focus();
  updateCount();
});

Preventing the default stops the page reload; trim() rejects whitespace-only entries; clearing the field and returning focus lets the user type the next task immediately.

Step 5: delegate the Done and Delete clicks

list.addEventListener('click', (event) => {
  const button = event.target.closest('button');
  if (!button) return;

  const li = button.closest('li');

  if (button.dataset.action === 'toggle') {
    li.classList.toggle('done');
  }
  if (button.dataset.action === 'delete') {
    li.remove();
  }
  updateCount();
});

Step 6: run it and check the behaviour

  • Submitting the form adds a row and the counter rises.
  • Clicking Done toggles the done class on that row only, and the counter falls or rises accordingly.
  • Clicking Delete removes the row and updates the counter.
  • Because the click listener lives on the <ul>, every newly added row works with no extra wiring.

One CSS rule completes the picture: .done span { text-decoration: line-through; }. JavaScript never touches the strikethrough directly — it only flips a class, and CSS decides what that class looks like.

20. Practice Exercises

  1. Build a colour theme switcher: three buttons, each adding a different class to the <body>, and CSS defining the colours.
  2. Extend the character counter so that a warning class is added to the counter when the text reaches the limit, and removed when it drops below.
  3. Create a FAQ accordion: clicking a question toggles the visibility of its answer, using one delegated listener on the container.
  4. Add a live filter to the task list: an input that hides every row whose text does not include the typed value (lowercase both sides before comparing).
  5. Add keyboard support to the task list: pressing Escape while typing clears the input field.
  6. Add a "Mark all done" button above the list that adds the done class to every row and updates the counter.
  7. Debug this brief: a teammate's code calls document.querySelector('.item'), then reads .textContent, and sometimes crashes with "cannot read properties of null". Identify the two likely causes and fix them.

21. Interview Questions and Answers

What is the DOM?

The Document Object Model is the browser's in-memory tree representation of an HTML page, with one object per element. JavaScript reads and modifies this tree, and the browser immediately reflects every change on screen. The HTML file is the source; the DOM is the live model the language actually works on.

What is the difference between querySelector and getElementById?

querySelector accepts any CSS selector and returns the first match, while getElementById accepts only an id string and returns that one element. For ids, getElementById is direct and fast; querySelector is more flexible because one method covers every selector you already know from CSS.

What is event bubbling?

When an event fires on an element, it does not stop there: after running on the target, it travels upward through the element's ancestors, giving each one a chance to run its own listeners. That upward journey is bubbling. It is why one listener on a parent can react to events on all of its children.

What is event delegation and why is it useful?

Delegation means attaching a single listener to a parent element and using event.target (usually with closest()) to work out which child was acted on. It reduces the number of listeners and, crucially, keeps working for children added to the page later, because the listener sits on the parent, not on the children.

What does event.preventDefault() do?

It cancels the browser's built-in default action for an event. The classic case is a form's submit event: by default the browser sends the data and reloads the page, and calling preventDefault() stops that so JavaScript can handle the data itself. It does not stop the event from bubbling — that is stopPropagation().

What is the difference between event.target and event.currentTarget?

event.target is the element where the event originated — the deepest element actually clicked. event.currentTarget is the element the running listener is attached to. On the target itself they are the same; on an ancestor handling a bubbled event they differ, and delegation relies on reading the target.

How do textContent and innerHTML differ?

textContent sets or returns plain text: any HTML in the string is shown literally as characters. innerHTML parses the string as HTML and builds real elements from it. Because of that, innerHTML with untrusted user input is a script-injection risk, so textContent is the safe default for text.

How do you add and remove an event listener?

You add one with element.addEventListener('click', handler). To remove it, removeEventListener must receive the same function reference, which means the handler must be stored in a variable or named function — an inline arrow function cannot be removed later. For one-shot listeners, an options object with once: true is cleaner.

What is the difference between the input and change events?

input fires immediately on every change of a field's value, effectively every keystroke, which suits live counters and search filtering. change fires when the value is committed, typically when the field loses focus, which suits validating a finished entry.

What is a NodeList and how does it differ from an array?

querySelectorAll returns a NodeList, a collection of nodes. It supports forEach and index access but lacks array methods such as map, filter and reduce. When those are needed, convert it with spread — [...nodes] — or Array.from(nodes).

What are the capturing and bubbling phases?

An event travels in phases: first down the tree from the document to the target (capturing), then it fires on the target, then up through the ancestors (bubbling). Listeners run during bubbling by default, which is the phase everyday code and delegation rely on; capturing exists for special cases and rarely needs to be used directly.

Why does DOM and event knowledge matter when you will write React?

React manages the same DOM you manipulate by hand here — it simply automates the updating. Understanding selection, events, bubbling and preventDefault() explains what React is doing for you, makes its event handling intuitive, and is exactly the JavaScript baseline interviewers expect before React questions begin.

22. Quick Revision Checklist

  • I can explain the DOM as a live tree of objects built from HTML.
  • I can select elements with querySelector, querySelectorAll and getElementById, and say what each returns.
  • I know querySelector returns null on no match, and I check for it.
  • I can read and change textContent, classList, style and attributes.
  • I can create elements with createElement, attach them with append, and remove them with remove.
  • I can register a listener with addEventListener and name the event type correctly, without "on".
  • I can use the event object: type, target, key, preventDefault().
  • I can explain bubbling and use delegation with closest() on a parent element.
  • I know the difference between input and change, and between textContent and innerHTML.
  • I can build a small interactive feature following select, listen, update.

23. Official Documentation and Further Reading

These resources from the course reading list connect this page to the React training ahead:

Conclusion

This page gave you the two verbs of browser programming: select and listen. You can now find any element with CSS selectors, walk the tree from any reference, create and remove nodes, register listeners for clicks, keys, input and submit, read the event object, cancel default behaviour, and scale up cleanly with delegation. The rhythm to carry forward is always the same: select an element, listen for an event, update the page.

Everything here runs on the same DOM that React manages for you, so this knowledge keeps paying off throughout the course. The next page in this module, Fetch API & JSON, adds the third ingredient: getting real data from a server and rendering it into the elements you now know how to select and update.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp