DOM Manipulation and EventsLesson 5.1
Understanding the DOM: Structure and Selection
What is the DOM, DOM tree, selecting elements with querySelector, querySelectorAll, getElementById, getElementsByClassName
Understanding the DOM: Structure and Selection
The Document Object Model (DOM) is a programming interface that represents an HTML document as a tree of objects. When a browser loads an HTML file, it parses the markup and builds the DOM tree. JavaScript can then read and modify this tree, enabling dynamic web pages.
The DOM Tree
Every HTML element becomes a node in the DOM tree. The document object is the root. From it, you access the html element, which contains head and body, and so on. Text content inside elements is also a node, called a text node.
Selecting Elements
// Select a single element by CSS selector
const heading = document.querySelector('h1');
const btn = document.querySelector('#submit-btn');
const firstCard = document.querySelector('.card');
// Select multiple elements
const allCards = document.querySelectorAll('.card');
// Legacy methods (still useful)
const header = document.getElementById('main-header');
const paragraphs = document.getElementsByTagName('p');Reading and Writing Content
const heading = document.querySelector('h1');
console.log(heading.textContent); // read text
heading.textContent = 'Updated Heading'; // write text
const container = document.querySelector('#app');
container.innerHTML = '<p>New <strong>content</strong> here.</p>';Reading and Modifying Attributes
const link = document.querySelector('a');
console.log(link.getAttribute('href'));
link.setAttribute('href', 'https://example.com');
link.setAttribute('target', '_blank');
const img = document.querySelector('img');
img.src = 'new-image.jpg';
img.alt = 'A description';Working with CSS Classes
const card = document.querySelector('.card');
card.classList.add('active');
card.classList.remove('hidden');
card.classList.toggle('expanded');
console.log(card.classList.contains('active')); // true