Reference article · Programming
DOM and events: connect JavaScript to HTML
The DOM represents a document through browser APIs. JavaScript can read fields, change text and respond to interaction without reloading the page.
Selecting an element
document.querySelector accepts a CSS selector and returns the first matching element, or null. # selects an id; a dot selects a class. Check the result before using it.
Listening for events
addEventListener registers a function to run on events such as click or input. Pass the function without immediately calling it. The event object provides information; event.target identifies the object the event was dispatched to.
Complete counter example
Place this inside an HTML document. The script comes after the elements, so they exist when selected. Each click increments the counter and replaces the paragraph’s text.
<button id="add" type="button">Add visit</button>
<p id="result" aria-live="polite">Visits: 0</p>
<script>
const button = document.querySelector("#add");
const result = document.querySelector("#result");
let visits = 0;
if (button && result) {
button.addEventListener("click", () => {
visits += 1;
result.textContent = "Visits: " + visits;
});
}
</script>Text and HTML behave differently
textContent inserts text without parsing tags. innerHTML parses HTML, so do not directly insert untrusted content through it. For a plain name or message, textContent avoids that interpretation.
Common mistakes and practice
- If selection returns null, check the selector and script timing.
- Verify each click adds one visit; registering behaviour repeatedly can duplicate it.
- Add a reset button and try keyboard interaction.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
