- Explain what the DOM is
- Find elements with
querySelectorand 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?
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.
document
└── html
├── head
│ └── title
└── body
├── h1
└── ul
├── li
└── lidocument 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.
<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>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:
<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>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.
<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>| Event | When it happens |
|---|---|
click | the element is clicked |
input | the text in a field changes — on every character |
submit | a form is submitted |
keydown | a key is pressed |
mouseover | the 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.
<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>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.
<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>item.remove()).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.
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. querySelectorreturns the first matching element,querySelectorAllreturns all of them.textContent,styleandclassListchange an element's text, styles and classes.createElementcreates an element,appendadds it to the page,removedeletes it.addEventListenerattaches a handler to an event;preventDefault()stops the browser's default behaviour.
Check yourself
10 questions. Every correct answer earns XP.