Interacting with the DOM
The Document Object Model (DOM) represents the page as a tree of nodes. You can query elements, listen for events, and modify the page structure or content on the fly.
// Select elements
const button = document.querySelector('button');
const items = document.querySelectorAll('.item');
// Event handling
button.addEventListener('click', () => {
items.forEach(item => item.classList.toggle('active'));
});
// Creating elements
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
document.querySelector('ul').appendChild(newItem);
// Updating elements
const heading = document.getElementById('main-heading');
heading.textContent = 'Updated Title';
Key Methods
querySelector
,querySelectorAll
— select elements using CSS selectorsgetElementById
,getElementsByClassName
— legacy selection methodsaddEventListener
— attach event listeners to elementscreateElement
,appendChild
,removeChild
— dynamically add or remove nodestextContent
,innerHTML
— update element content