Learning how to work with the DOM using plain JavaScript is essential. It gives you the ability to build fast, responsive websites without needing extra tools. Once you have the basics down and understand how to keep your code performant, you will have a set of skills that works for any project. Keep practicing and exploring how the browser handles your changes.
Introduction
Changing the Document Object Model (DOM) is a skill every web developer needs. Frameworks can make things easier, but knowing how to use plain JavaScript gives you more control. You will be able to fix performance bugs and understand exactly how your code interacts with the browser. This guide covers the basics and best practices for working with the DOM without any extra libraries.
Understanding the DOM
What is the DOM
The DOM is how the browser sees your HTML file as a tree. Every tag, attribute, and bit of text is a piece of that tree called a node. JavaScript lets you talk to these nodes. When you change a node, the browser updates the page immediately.
Why use vanilla JavaScript
- Speed: Talking to the browser directly is faster because there is no middleman software slowing things down.
- Reliability: Plain JavaScript works in any browser. You don't have to worry about whether a specific library is loaded or compatible.
- Stronger skills: Once you know how the browser actually works, using frameworks like React or Vue becomes much easier to understand.
Core Methods for Selecting Elements
First, you need to find the element you want to change. Here are the most common ways to do that:
- `document.getElementById(id)` finding a single element by its ID is the fastest way.
- `document.getElementsByClassName(className)` this gets every element that uses a specific class.
- `document.getElementsByTagName(tagName)` use this to find elements by their tag, like all `<p>` tags.
- `document.querySelector(cssSelector)` this is very flexible and finds the first element that matches a CSS-style selector.
- `document.querySelectorAll(cssSelector)` similar to the one above, but it gives you a list of every matching element it finds.
Stick with `querySelector` for most things. If you know exactly which ID you need, `getElementById` is slightly more efficient.
Manipulating Content and Attributes
After you select an element, you can swap its text or change its settings. These are the tools you will use most often:
- `element.textContent` use this to read or change the plain text inside an element.
- `element.innerText` this also handles text, but it pays attention to whether the text is actually visible on the screen.
- `element.innerHTML` this lets you add HTML tags directly. Be careful with this, as it can be a security risk if you are using data from users.
- `element.setAttribute(name, value)` this is how you add or change attributes like `src` or `href`.
- `element.getAttribute(name)` this tells you the current value of an attribute.
- `element.removeAttribute(name)` this removes an attribute entirely.
If you are building a lot of content at once, it is usually cleaner to create the nodes first and then put them on the page all at once.
Handling Classes and Styles
You will often need to turn classes on and off to make a page interactive. The `classList` tool is the best way to handle this:
- `element.classList.add()` use this to give an element a new class.
- `element.classList.remove()` this takes a class away.
- `element.classList.toggle()` if the class is there, it removes it. If it isn't, it adds it. It is perfect for buttons that open and close menus.
- `element.classList.contains()` this just checks if a class is already being used.
You can also change styles directly in JavaScript:
- `element.style.property = value` use this to change a single style, like the color of text.
- `element.style.cssText` this allows you to write out several styles in one line.
Try to stick to changing classes. It keeps your design logic in your CSS file and your behavior logic in your JavaScript file.
Event Handling Basics
When someone clicks a button or types in a box, an event happens. You can listen for these using `addEventListener` without breaking other parts of your code:
- `element.addEventListener()` this tells the browser to run a function when a specific event occurs.
- `element.removeEventListener()` this stops the browser from listening to that event.
- `event.stopPropagation()` this keeps an event from triggering listeners on parent elements.
- `event.preventDefault()` this stops the browser from doing what it normally does, like refreshing the page when a form is sent.
Event Delegation
If you have a lot of items, don't put a listener on every single one. Instead, put one listener on the parent container. Use `event.target` to see which child was clicked. It saves memory and makes it easier to add new items later.
```javascript
document.body.addEventListener('click', function (e) {
if (e.target.matches('.button')) {
// handle button click
}
});
```
Performance Considerations
Changing the DOM too much can make a website feel laggy. Here is how to keep things fast:
- Update in batches: Make all your changes at once rather than one by one.
- Use fragments: A `DocumentFragment` is like a staging area. You can build your new elements there and then move them onto the page in one go.
- Watch your order: Read information about the layout, like an element's height, before you write new styles.
- Avoid jumping back and forth: Don't mix reading and writing layout properties inside a loop.
- Sync with the browser: Use `requestAnimationFrame` for animations so they match the browser's refresh rate.
Best Practices and Common Pitfalls
- Stay safe: If you use `innerHTML`, make sure you aren't accidentally letting a user inject their own code.
- Use textContent: It is faster and more reliable than `innerText` for simple text changes.
- Update offline: Sometimes it is faster to remove an element from the page, change it, and then put it back.
- Save your elements: If you need an element more than once, save it in a variable so you don't have to search for it again.
- Scope your variables: Use `const` and `let` to keep your code organized and prevent bugs.
- Think about everyone: When you change content, remember to update ARIA labels so screen readers stay accurate.
Following these simple steps will help you write code that is clean, secure, and fast.
Conclusion
Learning how to work with the DOM using plain JavaScript is essential. It gives you the ability to build fast, responsive websites without needing extra tools. Once you have the basics down and understand how to keep your code performant, you will have a set of skills that works for any project. Keep practicing and exploring how the browser handles your changes.