Making Pages Interactive with the DOM
Connecting JavaScript to the Page
The DOM (Document Object Model) is the browser's live representation of your HTML page as a tree of objects. JavaScript uses the DOM to read and change the page after it has loaded.
Selecting Elements
The method document.querySelector() finds the first element that matches a CSS-style selector.
const title = document.querySelector("h1");
const btn = document.querySelector(".action-button");Changing Content and Style
Once you have an element, you can change its text with textContent or its appearance through the style property.
title.textContent = "Updated by JavaScript!";
title.style.color = "green";Responding to Events
An event is something that happens on the page, such as a click or a key press. The addEventListener() method runs a function when a chosen event occurs.
const btn = document.querySelector(".action-button");
btn.addEventListener("click", function () {
alert("Button was clicked!");
});The function passed to addEventListener is called a handler. It does not run immediately — the browser stores it and runs it each time the event happens.
A Complete Mini Example
This counter increases a number every time a button is clicked.
<p id="display">0</p>
<button id="plus">Add One</button>let count = 0;
const display = document.querySelector("#display");
const plusBtn = document.querySelector("#plus");
plusBtn.addEventListener("click", function () {
count = count + 1;
display.textContent = count;
});Common Events
click— the user clicks an element.input— the user types into a text field.submit— a form is submitted.mouseover— the pointer moves onto an element.
Place your<script>tag just before the closing</body>tag. That way the HTML elements already exist when your JavaScript tries to select them.
Discussion
0No comments yet — be the first to leave one!