Selecting elements
const title = document.querySelector('h1');
title.textContent = 'Updated Title via JS';
Handling events
Try this interactive example:
const input = document.getElementById('name');
const btn = document.getElementById('greetBtn');
const out = document.getElementById('output');
btn.addEventListener('click', () => {
const value = input.value.trim();
out.textContent = value ? `Hello, ${value}!` : 'Please enter your name.';
});
Practice ideas
- Build a simple counter with + and − buttons.
- Create a todo list where you can add and remove items.
- Toggle a dark mode class on the
bodywhen clicking a switch.
Quick Check
Which method attaches an event handler to an element?