Working with the DOM in JavaScript
Introduction
The Document Object Model (DOM) is the browser's live representation of your HTML page. With JavaScript you can read and change it to make pages interactive. This tutorial covers selecting elements, updating them, creating new ones, and reacting to events.
Prerequisites
- Basic HTML and CSS
- JavaScript functions and variables
- A browser with developer tools
Step-by-Step Guide
Step 1: Select elements
querySelector returns the first element matching a CSS selector. querySelectorAll returns all matches.
const title = document.querySelector("h1");
const items = document.querySelectorAll(".item");Step 2: Change text and classes
Set textContent to change an element's text, and use classList to add, remove, or toggle CSS classes.
title.textContent = "Welcome to CaliberTek";
title.classList.add("highlight");Step 3: Create and add new elements
Create an element, configure it, then attach it to the page with appendChild or append.
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").appendChild(li);Step 4: Respond to events
addEventListener runs a function when something happens, such as a click.
const button = document.querySelector("#save");
button.addEventListener("click", () => {
console.log("Saved!");
});Step 5: Remove elements
Call remove() on an element to delete it from the page.
li.remove();FAQs
- What is the difference between textContent and innerHTML?
- textContent inserts plain text and is safe for user input. innerHTML parses HTML and can introduce cross-site scripting (XSS) vulnerabilities if you insert untrusted content.
- Why does my script say an element is null?
- The script ran before the element existed. Place the script at the end of the body, or add the defer attribute to the script tag so it runs after the page is parsed.
Summary
Select what you need, update it with textContent and classList, create elements when needed, and wire up behavior with event listeners. Prefer textContent when inserting text you don't fully control.
Comments
Log in or create a free account to join the discussion.