What you will learn
- Select elements with querySelector and querySelectorAll
- Change text, attributes and classes on the page
- Respond to user actions with addEventListener
When a browser loads HTML, it builds the Document Object Model, or DOM, a tree of objects representing every element. JavaScript can read and change this tree. document.querySelector(".menu-button") returns the first element matching a CSS selector, and querySelectorAll returns all matches. Once you have an element, you can change its textContent, its attributes, or its classes through classList.
Events connect your code to what people do. button.addEventListener("click", () => { ... }) runs a function each time the button is clicked. Other common events include input on text fields, submit on forms and keydown on the keyboard. For a form, call event.preventDefault() inside the submit handler if you want to handle the data with JavaScript instead of reloading the page.
A clean pattern is to keep styling in CSS and use JavaScript only to toggle classes. For the mobile menu from the last module, a click handler can run menu.classList.toggle("hidden") and update the button's aria-expanded attribute to true or false. To add content, create elements with document.createElement and append them. Use textContent rather than innerHTML for user-supplied text to avoid injecting unsafe code.


