9.1 DOM Manipulation
DOM (Document Object Model): Represents HTML as objects that JavaScript can interact
with.
Selecting Elements:
- getElementById(id) - Select by ID
- getElementsByClassName(class) - Select by class (returns HTMLCollection)
- querySelector(selector) - Select first matching element
- querySelectorAll(selector) - Select all matching elements
Modifying Content:
- innerHTML - Get/set HTML content (use carefully)
- innerText - Get/set plain text content
- textContent - Get/set text (includes hidden elements)
Attributes:
- setAttribute(name, value) - Set attribute
- getAttribute(name) - Get attribute value
- removeAttribute(name) - Remove attribute
- Direct property access: element.id, element.class
Styling:
- element.style.color = "red" - Inline styles
- element.classList.add/remove/toggle() - Manage CSS classes
- element.className - Get/set class attribute
Creating & Removing Elements:
- createElement(tag) - Create new element
- appendChild(child) - Add child element
- removeChild(child) - Remove child element
- insertBefore(new, reference) - Insert before element
Practice Problems (Practical 20-22)
Practical 20: Handle keyboard events:
i) Display key code for pressed key
ii) If key is vowel (a,e,i,o,u), announce it
iii) On key release, background changes to blue
Practical 21: Handle mouse events:
i) Click heading: change text to "Hello World" (italic, 50px)
ii) Click "red" button: heading turns red
iii) Click "blue" button: heading turns blue
Practical 22: Create HTML with h1, p, button, ul. On button click:
- Change heading text
- Change all paragraphs to red color
- Change first paragraph background color
- Underline all list items
Q1: Difference between getElementById and querySelector.
Q2: What is innerHTML? Why should it be used carefully?
Q3: Explain event delegation in JavaScript.
Q4: What does event.preventDefault() do?
Q5: How do you dynamically create and add elements to the DOM?
Q6: Difference between mouseover and mouseenter events.
Q7: How do you add/remove/toggle CSS classes using JavaScript?
Q8: Explain event bubbling and event capturing.