Changing the page
Find elements, react to clicks and update what is shown.
The DOM is the browser's live model of your page. JavaScript can find any element in it and change it.
HTML
<button id="btn">Clicked 0 times</button>
<script>
const btn = document.querySelector("#btn");
let count = 0;
btn.addEventListener("click", () => {
count += 1;
btn.textContent = `Clicked ${count} times`;
});
</script>| Code | Does |
|---|---|
document.querySelector(".x") | Finds the first match |
el.textContent = "Hi" | Sets plain text, which is safe |
el.classList.toggle("open") | Adds or removes a class |
el.addEventListener("click", fn) | Runs fn on each click |
form.addEventListener("submit", fn) | Handles a form; call event.preventDefault() first |
Use textContent for anything a user typed. Putting user text into innerHTML lets an attacker run scripts on your page, which is called cross-site scripting.