The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree-like hierarchy, allowing developers to access and manipulate the content, structure, and style of web pages dynamically.
Let's start with some basic DOM manipulation techniques:
To interact with DOM elements, we first need to select them. Here are some common methods:
// Select by ID const element = document.getElementById('myElement'); // Select by class name const elements = document.getElementsByClassName('myClass'); // Select by tag name const paragraphs = document.getElementsByTagName('p'); // Select using CSS selectors const firstButton = document.querySelector('button'); const allButtons = document.querySelectorAll('button');
Once we've selected an element, we can modify its content:
// Change text content element.textContent = 'New text content'; // Change HTML content element.innerHTML = '<strong>New HTML content</strong>';
We can also change element attributes:
// Set an attribute element.setAttribute('class', 'newClass'); // Get an attribute value const href = element.getAttribute('href'); // Remove an attribute element.removeAttribute('disabled');
Changing element styles is straightforward:
// Change a single style property element.style.color = 'red'; // Change multiple style properties Object.assign(element.style, { fontSize: '16px', fontWeight: 'bold', backgroundColor: '#f0f0f0' });
To create new elements dynamically:
// Create a new element const newParagraph = document.createElement('p'); newParagraph.textContent = 'This is a new paragraph.'; // Append the new element to an existing element document.body.appendChild(newParagraph);
To remove elements from the DOM:
// Remove an element element.remove(); // Remove a child element parentElement.removeChild(childElement);
Event handling is crucial for creating interactive web applications. Let's explore some key concepts:
To respond to user actions, we add event listeners to elements:
const button = document.querySelector('button'); button.addEventListener('click', function() { console.log('Button clicked!'); });
It's important to remove event listeners when they're no longer needed:
function handleClick() { console.log('Button clicked!'); } button.addEventListener('click', handleClick); // Later, when you want to remove the listener button.removeEventListener('click', handleClick);
The event object contains useful information about the event:
button.addEventListener('click', function(event) { console.log('Event type:', event.type); console.log('Target element:', event.target); console.log('Mouse coordinates:', event.clientX, event.clientY); });
Event delegation is a powerful technique for handling events on multiple elements efficiently:
document.getElementById('parent-list').addEventListener('click', function(event) { if (event.target.tagName === 'LI') { console.log('Clicked on list item:', event.target.textContent); } });
Let's put it all together with a simple todo list application:
const todoForm = document.getElementById('todo-form'); const todoInput = document.getElementById('todo-input'); const todoList = document.getElementById('todo-list'); todoForm.addEventListener('submit', function(event) { event.preventDefault(); if (todoInput.value.trim() === '') return; const todoItem = document.createElement('li'); todoItem.textContent = todoInput.value; const deleteButton = document.createElement('button'); deleteButton.textContent = 'Delete'; deleteButton.addEventListener('click', function() { todoList.removeChild(todoItem); }); todoItem.appendChild(deleteButton); todoList.appendChild(todoItem); todoInput.value = ''; });
This example demonstrates how to create elements, handle form submissions, and dynamically update the DOM.
By mastering these DOM manipulation and event handling techniques, you'll be well-equipped to create dynamic and interactive web applications using vanilla JavaScript. Remember to practice these concepts regularly and explore more advanced topics to further enhance your skills.
14/09/2024 | VanillaJS
15/10/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS
15/10/2024 | VanillaJS
15/10/2024 | VanillaJS
15/10/2024 | VanillaJS
15/10/2024 | VanillaJS
15/10/2024 | VanillaJS