Welcome to our JS DOM HTML tutorial! This guide will help you understand the Document Object Model (DOM) and how to manipulate HTML elements using JavaScript. Let's dive in! 🐳
The DOM is a programming interface for HTML and XML documents. It represents the structure of a document as a tree-like model, where each element is an object. This allows us to manipulate HTML elements programmatically.
To interact with HTML elements using JavaScript, we first need to access them. We can do this using the document.querySelector() and document.querySelectorAll() methods.
document.querySelector() 💡This method returns the first element that matches the specified selector.
Example:
// Select the first paragraph
const paragraph = document.querySelector('p');document.querySelectorAll() 💡This method returns all elements that match the specified selector.
Example:
// Select all links
const links = document.querySelectorAll('a');Once we've accessed an HTML element, we can manipulate it using various JavaScript methods. Here are some examples:
element.textContentelement.innerHTMLelement.style.propertyNameelement.classList.add('class-name')element.classList.remove('class-name')Example:
// Change the text content of the first paragraph
const paragraph = document.querySelector('p');
paragraph.textContent = 'Hello, World!';
// Change the color of all links
const links = document.querySelectorAll('a');
links.forEach(link => link.style.color = 'red');What does `document.querySelectorAll()` return?
Events are actions that occur in a document, such as clicking a button or loading a page. JavaScript allows us to respond to these events using event listeners.
Event listeners are functions that execute when an event occurs. We can attach an event listener to an HTML element using the addEventListener() method.
Example:
// Attach a click event listener to a button
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button clicked!');
});How can you attach an event listener to an HTML element?
Now that you've learned the basics of the DOM and HTML manipulation with JavaScript, it's time to put your knowledge into practice. Here's a small project idea:
Create a simple to-do list application where users can add, remove, and mark tasks as completed. Use the DOM to manipulate the HTML and add event listeners for interaction.
Happy coding! 🎉