What is DOM?
Imagine an HTML document as a family tree. Each element has a parent, and there may be children and neighbors. DOM is a way for the browser to organize all the elements of the page as JavaScript objects that you can work with.
<!DOCTYPE html>
<html>
<body>
<h1>Привет, мир!</h1>
<p>Это параграф</p>
</body>
</html>In this example, <body> is the parent for <h1> and <p>, and they are its children.
Search for items on the page
Before you can change anything, you need to find the element. There are several ways to do this:
// Search by ID
const header = document.getElementById('main-header');
// Search by class (will return a collection of elements)
const buttons = document.getElementsByClassName('btn');
// Search by tag
const paragraphs = document.getElementsByTagName('p');
// Modern methods (the most popular!)
const firstButton = document.querySelector('.btn'); // first element
const allButtons = document.querySelectorAll('.btn'); // all itemsThe querySelector and querySelectorAll methods are your best friends. They work with any CSS selectors and are very convenient.
Change of content
Now that we've found the element, let's do something with it:
const title = document.querySelector('h1');
// Edit text
title.textContent = 'New title';
// Edit HTML (you can insert tags)
title.innerHTML = 'Title with <span>accent</span>';Important: use textContent for plain text and innerHTML only when you really need to insert HTML. It's safer.
Working with attributes
Attributes of elements are also easy to change:
const link = document.querySelector('a');
// Get attribute
const href = link.getAttribute('href');
// Set attribute
link.setAttribute('href', 'https://example.com');
// Remove attribute
link.removeAttribute('target');
// Working with classes
link.classList.add('active');
link.classList.remove('disabled');
link.classList.toggle('highlighted'); // switch classChange styles
CSS styles can be changed directly from JavaScript:
const box = document.querySelector('.box');
// Change one style
box.style.backgroundColor = 'blue';
box.style.width = '200px';
// The best way is through classes
box.classList.add('big-box');Tip: try to change styles through classes, not directly. This makes the code easier to maintain.
Creating new elements
You can create elements from scratch and add them to the page:
// Create item
const newDiv = document.createElement('div');
// Add content
newDiv.textContent = 'I am a new element!';
newDiv.classList.add('message');
// Add to page
document.body.appendChild(newDiv); // to the end of the body
// Or paste in a specific place
const container = document.querySelector('.container');
container.appendChild(newDiv);Deleting items
Items can be deleted:
const oldElement = document.querySelector('.old');
// Modern way
oldElement.remove();
// The old way (works everywhere)
oldElement.parentNode.removeChild(oldElement);
Case study: task list
Let's create a simple application for a task list. Try it yourself:
My tasks
Here is the code that makes this application work:
const input = document.getElementById('taskInput');
const addBtn = document.getElementById('addBtn');
const taskList = document.getElementById('taskList');
addBtn.addEventListener('click', function() {
const taskText = input.value.trim();
if (taskText === '') return;
// Create a new list item
const li = document.createElement('li');
li.textContent = taskText;
// We are adding the ability to mark a task
li.addEventListener('click', function() {
li.classList.toggle('completed');
});
// Delete button
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.className = 'delete-btn';
deleteBtn.addEventListener('click', function(e) {
e.stopPropagation(); // so that the click on li does not work
li.remove();
});
li.appendChild(deleteBtn);
taskList.appendChild(li);
// Clearing the input field
input.value = '';
});
// Add by Enter
input.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
addBtn.click();
}
});Useful tips
Cache elements. If you use an element several times, save it in a variable instead of searching again.
// Bad
document.querySelector('.box').style.width = '100px';
document.querySelector('.box').style.height = '100px';
// Good
const box = document.querySelector('.box');
box.style.width = '100px';
box.style.height = '100px';Use event delegation. Instead of adding handlers to each element, add one to the parent.
Minimize reflow. Frequent DOM changes can slow down the page. Group changes or use DocumentFragment.
Check for the existence of elements before working with them to avoid mistakes.
const element = document.querySelector('.maybe-exists');
if (element) {
element.textContent = 'Found it!';
}Conclusion
DOM manipulation is the basis of interactive web pages. With their help, you can create dynamic interfaces, respond to user actions and make sites live. Practice, experiment with examples, and soon it will become natural for you.
You can learn Python and other languages in Codice - we have a convenient platform for training with practical tasks.
And we also have a cool Telegram channel with a friendly community where you can ask questions, share experiences and grow together with like-minded people.
Join us!
