In this section, we will explore how to select and manipulate elements in the Document Object Model (DOM) using JavaScript. This is a fundamental skill for creating dynamic and interactive web applications.
Key Concepts
-
DOM Selection Methods
getElementById
getElementsByClassName
getElementsByTagName
querySelector
querySelectorAll
-
Manipulating DOM Elements
- Changing element content
- Modifying element attributes
- Changing styles
- Adding and removing classes
-
Practical Examples
- Selecting elements
- Changing text content
- Modifying attributes
- Changing styles dynamically
- Adding and removing classes
-
Exercises
- Practice selecting and manipulating DOM elements
DOM Selection Methods
getElementById
Selects an element by its ID.
getElementsByClassName
Selects all elements with a specific class name. Returns an HTMLCollection.
getElementsByTagName
Selects all elements with a specific tag name. Returns an HTMLCollection.
querySelector
Selects the first element that matches a CSS selector.
querySelectorAll
Selects all elements that match a CSS selector. Returns a NodeList.
Manipulating DOM Elements
Changing Element Content
Use the innerHTML
or textContent
properties to change the content of an element.
let element = document.getElementById('myElement'); element.innerHTML = 'New Content'; element.textContent = 'New Text Content';
Modifying Element Attributes
Use the setAttribute
and getAttribute
methods to modify attributes.
let element = document.querySelector('img'); element.setAttribute('src', 'newImage.jpg'); let src = element.getAttribute('src'); console.log(src);
Changing Styles
Use the style
property to change the CSS styles of an element.
let element = document.getElementById('myElement'); element.style.color = 'red'; element.style.backgroundColor = 'yellow';
Adding and Removing Classes
Use the classList
property to add or remove classes.
let element = document.querySelector('.myClass'); element.classList.add('newClass'); element.classList.remove('oldClass');
Practical Examples
Example 1: Selecting Elements
<!DOCTYPE html> <html> <head> <title>DOM Selection Example</title> </head> <body> <div id="myElement">Hello World</div> <div class="myClass">Class Element 1</div> <div class="myClass">Class Element 2</div> <script> let elementById = document.getElementById('myElement'); console.log(elementById); let elementsByClassName = document.getElementsByClassName('myClass'); console.log(elementsByClassName); let elementsByTagName = document.getElementsByTagName('div'); console.log(elementsByTagName); let elementByQuerySelector = document.querySelector('.myClass'); console.log(elementByQuerySelector); let elementsByQuerySelectorAll = document.querySelectorAll('.myClass'); console.log(elementsByQuerySelectorAll); </script> </body> </html>
Example 2: Manipulating Elements
<!DOCTYPE html> <html> <head> <title>DOM Manipulation Example</title> </head> <body> <div id="myElement">Hello World</div> <img id="myImage" src="oldImage.jpg" alt="Old Image"> <button id="changeContent">Change Content</button> <button id="changeImage">Change Image</button> <button id="changeStyle">Change Style</button> <button id="toggleClass">Toggle Class</button> <script> document.getElementById('changeContent').addEventListener('click', function() { let element = document.getElementById('myElement'); element.innerHTML = 'New Content'; }); document.getElementById('changeImage').addEventListener('click', function() { let image = document.getElementById('myImage'); image.setAttribute('src', 'newImage.jpg'); }); document.getElementById('changeStyle').addEventListener('click', function() { let element = document.getElementById('myElement'); element.style.color = 'blue'; element.style.backgroundColor = 'lightgray'; }); document.getElementById('toggleClass').addEventListener('click', function() { let element = document.getElementById('myElement'); element.classList.toggle('highlight'); }); </script> </body> </html>
Exercises
Exercise 1: Selecting Elements
- Create an HTML file with multiple elements.
- Use different DOM selection methods to select these elements.
- Log the selected elements to the console.
Exercise 2: Manipulating Elements
- Create an HTML file with a few elements and buttons.
- Write JavaScript to change the content, attributes, styles, and classes of these elements when the buttons are clicked.
Solutions
Solution 1: Selecting Elements
<!DOCTYPE html> <html> <head> <title>Exercise Solution</title> </head> <body> <div id="element1">Element 1</div> <div class="elementClass">Element 2</div> <div class="elementClass">Element 3</div> <p>Paragraph</p> <script> let elementById = document.getElementById('element1'); console.log(elementById); let elementsByClassName = document.getElementsByClassName('elementClass'); console.log(elementsByClassName); let elementsByTagName = document.getElementsByTagName('div'); console.log(elementsByTagName); let elementByQuerySelector = document.querySelector('.elementClass'); console.log(elementByQuerySelector); let elementsByQuerySelectorAll = document.querySelectorAll('.elementClass'); console.log(elementsByQuerySelectorAll); </script> </body> </html>
Solution 2: Manipulating Elements
<!DOCTYPE html> <html> <head> <title>Exercise Solution</title> </head> <body> <div id="element1">Element 1</div> <img id="image1" src="oldImage.jpg" alt="Old Image"> <button id="changeContent">Change Content</button> <button id="changeImage">Change Image</button> <button id="changeStyle">Change Style</button> <button id="toggleClass">Toggle Class</button> <script> document.getElementById('changeContent').addEventListener('click', function() { let element = document.getElementById('element1'); element.innerHTML = 'New Content'; }); document.getElementById('changeImage').addEventListener('click', function() { let image = document.getElementById('image1'); image.setAttribute('src', 'newImage.jpg'); }); document.getElementById('changeStyle').addEventListener('click', function() { let element = document.getElementById('element1'); element.style.color = 'green'; element.style.backgroundColor = 'lightblue'; }); document.getElementById('toggleClass').addEventListener('click', function() { let element = document.getElementById('element1'); element.classList.toggle('highlight'); }); </script> </body> </html>
Conclusion
In this section, we covered how to select and manipulate DOM elements using JavaScript. You learned about various DOM selection methods and how to change element content, attributes, styles, and classes. These skills are essential for creating dynamic and interactive web applications. In the next section, we will dive into event handling, which will allow you to make your web pages even more interactive.
JavaScript: From Beginner to Advanced
Module 1: Introduction to JavaScript
- What is JavaScript?
- Setting Up Your Development Environment
- Your First JavaScript Program
- JavaScript Syntax and Basics
- Variables and Data Types
- Basic Operators
Module 2: Control Structures
Module 3: Functions
- Defining and Calling Functions
- Function Expressions and Arrow Functions
- Parameters and Return Values
- Scope and Closures
- Higher-Order Functions
Module 4: Objects and Arrays
- Introduction to Objects
- Object Methods and 'this' Keyword
- Arrays: Basics and Methods
- Iterating Over Arrays
- Array Destructuring
Module 5: Advanced Objects and Functions
- Prototypes and Inheritance
- Classes and Object-Oriented Programming
- Modules and Import/Export
- Asynchronous JavaScript: Callbacks
- Promises and Async/Await
Module 6: The Document Object Model (DOM)
- Introduction to the DOM
- Selecting and Manipulating DOM Elements
- Event Handling
- Creating and Removing DOM Elements
- Form Handling and Validation
Module 7: Browser APIs and Advanced Topics
- Local Storage and Session Storage
- Fetch API and AJAX
- WebSockets
- Service Workers and Progressive Web Apps (PWAs)
- Introduction to WebAssembly
Module 8: Testing and Debugging
Module 9: Performance and Optimization
- Optimizing JavaScript Performance
- Memory Management
- Efficient DOM Manipulation
- Lazy Loading and Code Splitting
Module 10: JavaScript Frameworks and Libraries
- Introduction to React
- State Management with Redux
- Vue.js Basics
- Angular Basics
- Choosing the Right Framework