The DOM: selecting and changing elements
Until now your code worked with data and showed results in the console. From this week JavaScript comes to life on the page. When the browser loads an HTML document, it builds a tree representation called the DOM (Document Object Model): each tag is a node that JavaScript can read, change, create or delete. Everything is accessed through the global document object. For this week you need two files in a folder: index.html and app.js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>DOM practice</title>
</head>
<body>
<h1 id="title">Hello</h1>
<p class="note">First note</p>
<p class="note">Second note</p>
<ul id="list"></ul>
<script type="module" src="app.js"></script>
</body>
</html>Notice that the script is at the end of the body and has type="module": that way the HTML already exists when the code runs. Modules are deferred automatically, but you need to open the page from a local server (for example npx serve) and not by double-clicking. If the script runs before the HTML, querySelector will return null and you will see errors like Cannot read properties of null.
Selecting elements
The most versatile method is querySelector, which receives a CSS selector and returns the first matching element (or null). querySelectorAll returns all of them in a NodeList, which you can walk with for...of or convert to an array with Array.from. There are also getElementById and getElementsByClassName, which are older. Once you have the element, you can change its text with textContent, its styles with style, and its classes with classList.
// app.js
const title = document.querySelector('#title');
const notes = document.querySelectorAll('.note');
title.textContent = 'Hello, DOM!';
title.style.color = 'tomato';
title.classList.add('big');
title.classList.toggle('big'); // removes it again
console.log(title.classList.contains('big')); // false
for (const note of notes) {
note.textContent = note.textContent.toUpperCase();
}
console.log(Array.from(notes).map((n) => n.textContent));
title.setAttribute('data-ready', 'yes');
console.log(title.getAttribute('data-ready')); // yesCreating and removing elements
To add new content, create the element with document.createElement, configure it and place it with append or prepend in the parent. To delete, call remove on the element. There is innerHTML, which inserts HTML as text, but be careful: if you insert text typed by a user, someone could inject malicious code (an XSS attack). For user text always use textContent, which treats the content as plain text and not as HTML.
const list = document.querySelector('#list');
const languages = ['JavaScript', 'Python', 'Go'];
for (const name of languages) {
const li = document.createElement('li');
li.textContent = name;
list.append(li);
}
list.firstElementChild.remove(); // deletes JavaScript
console.log(list.children.length); // 2
// Dangerous with user input:
// list.innerHTML = userText; // XSS riskWalking the tree and data attributes
Besides selecting with querySelector, you can move through the tree: parentElement goes up to the parent, children lists the children, nextElementSibling moves to the next sibling and closest looks for the nearest ancestor matching a selector. The data-* attributes are a clean way to store information in the HTML, for example data-id on each task, and they are read from JavaScript with the dataset property. Remember that dataset always returns text. By combining these tools you can locate any element starting from another, without needing to assign an id to everything.
const item = document.querySelector('#list li');
item.dataset.id = '42'; // creates data-id="42"
console.log(item.dataset.id); // '42' (text)
console.log(item.parentElement.id); // list
console.log(item.nextElementSibling); // the next li or null
console.log(item.closest('ul') === item.parentElement); // true✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف