Selecting & Modifying Elements
Learn to manipulate the DOM! Master querySelector, getElementById, innerHTML, style, and classList.
Learn to manipulate the DOM! Master querySelector, getElementById, innerHTML, style, and classList. This hands-on tutorial focuses on practical implementation of selecting & modifying elements concepts.
Selecting & Modifying Elements
To change anything on a web page, you follow a simple 2-step process:
- Select the element you want to change.
- Modify it (change text, style, or attributes).
1. Selecting Elements 🎯
There are many ways to find elements, but these two are the most important.
A. querySelector (The Modern Way)
Selects the first element that matches a CSS selector.
B. getElementById (The Fast Way)
Selects a specific element by its unique ID. It's slightly faster than querySelector but only works for IDs.
C. Selecting Multiple Elements
Use querySelectorAll to get a list of all matching elements.
2. Modifying Content 📝
Once you have an element, you can change what's inside it.
innerText: Changes the visible text.innerHTML: Changes the HTML (allows you to add tags like<b>).
3. Modifying Styles 🎨
You can change CSS directly using the .style property. Note that CSS properties use camelCase in JavaScript (e.g., background-color becomes backgroundColor).
4. Modifying Classes (Best Practice) 🏷️
Changing individual styles is messy. It's better to define classes in CSS and toggle them in JavaScript using classList.
add("class-name")remove("class-name")toggle("class-name")
Practical Example: Dark Mode Toggle 🌙
AI Mentor
Confused about "DOM manipulation, querySelector, innerHTML, style, and classList"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4Which method selects ALL matching elements?
Key Takeaways
✅ querySelector finds the first match.
✅ querySelectorAll finds all matches.
✅ innerText for text, innerHTML for HTML.
✅ style.property for quick fixes.
✅ classList for clean styling (Best Practice).
What's Next?
Now that we can change elements, let's make them respond to user actions with Events!
Keep coding! 🚀