# DOM and events

The DOM is the browser’s object representation of HTML. JavaScript can find nodes, create nodes, change text, and respond to user events.

# Find and create elements

const root = document.getElementById('root');
const button = document.querySelector('[data-action="add"]');
const items = document.querySelectorAll('li');

const item = document.createElement('li');
item.textContent = 'New item';
item.classList.add('item');
root.append(item);

Use textContent for plain user-provided text. innerHTML parses a string as HTML and should not receive untrusted content; it can create cross-site scripting vulnerabilities. innerText is layout-aware, while textContent reads and writes text nodes directly.

# Events

button.addEventListener('click', event => {
  event.preventDefault();
  event.currentTarget.classList.toggle('active');
});

An event has a type, target, and current target. The target is the originating element; the current target is the element whose listener is running. Event delegation places one listener on a parent and uses event.target to handle matching children.

# Coffee choices

The pet project uses checkboxes for coffee choices. The general pattern is:

const choice = document.querySelector('#choice');
const checkboxes = document.querySelectorAll('input[type="checkbox"]');

function renderChoices() {
  const selected = [...checkboxes]
    .filter(input => input.checked)
    .map(input => input.name);
  choice.textContent = selected.join(', ');
}

checkboxes.forEach(input => {
  input.addEventListener('change', renderChoices);
});

Elements can also be created in code with document.createElement, attached with append, and wired with addEventListener—useful when the list of choices is not known in advance.

# Exercise

Create a small page that renders selected coffee items immediately after checking or unchecking a box. Keep the rendered result synchronized with the current checkbox state and make the controls keyboard accessible.