DOM Manipulation
1 week BeginnerControl HTML elements from JS to dynamically update pages.
Overview
DOM (Document Object Model) is how JavaScript represents and interacts with HTML elements.
Without manipulating the DOM, you can't change what's on the screen. It's the foundation for frameworks like React.
- Selecting elements
- Event listeners
- Changing classes and styles
- Creating and removing elements
Detailed Explanation
Selecting Elements
Bring HTML elements into JS. Grab one by ID, or use querySelector like CSS selectors.
- document.getElementById('msg')
- document.querySelectorAll('li')
- querySelectorAll returns a NodeList, which you can iterate with forEach
- Trying to manipulate an element that wasn't found (null reference error)
Events (Clicking, Typing)
Running code when something happens (e.g. 'Button clicked') is called listening for an event.
- btn.addEventListener('click', () => {\n console.log('Clicked');\n})
- Event Delegation: attaching one listener to a parent lists (ul) instead of all children
Modifying, Adding, Removing
Use textContent for text, classList.add for CSS classes. Use createElement to make new boxes, and remove() to delete them.
- el.textContent = 'Hello'
- el.classList.add('active')
- el.remove()
- Combining class toggling with CSS transitions creates easy animations
- Using innerHTML directly with user input, creating security holes (XSS)
Practical Steps
- 1 Grab an element and change its text 3 mins
Use JS to find an HTML element and forcefully change its content.
- Create a <p> with an ID
- Find it using getElementById
- Change its textContent
<p id="message">Old text...</p> <script> const pTag = document.getElementById('message'); pTag.textContent = 'Hacked by JavaScript!'; </script> - 2 Change CSS with JavaScript 3 mins
Make a box turn red and bold just by using JS.
- Find the element
- Modify its style property
<div id="box">I am a box</div> <script> const box = document.getElementById('box'); // Notice how background-color becomes backgroundColor in JS (camelCase) box.style.backgroundColor = 'red'; box.style.color = 'white'; box.style.fontWeight = 'bold'; </script> - 3 Listen for Clicks 5 mins
The holy grail of interactivity: doing something *only* when a button is clicked.
- Create a button with an ID
- Attach an 'addEventListener' for the 'click' event
- Show an alert
<button id="btn">Click Me</button> <script> const btn = document.getElementById('btn'); btn.addEventListener('click', () => { alert('Boom! Button clicked!'); }); </script>
Frequently Asked Questions
- People yelled at me for using innerHTML. What's wrong with it?
- textContent safely spits out whatever text you give it. innerHTML actually executes it as HTML. If you grab user input (like a comment section) and use innerHTML, a troll could inject a malicious script (XSS attack) that steals your users' data. It's highly dangerous.
- I added a new button with JS, but my click event isn't firing on it!
- If you set up `addEventListener` *before* the new button was created, JS didn't know it existed. The pro move is 'Event Delegation': attach the listener to the parent container, and when a click happens, check if the target (`e.target`) was your new button.
- I used querySelectorAll to get divs, then tried to map() over them and it crashed.
- Trick question! React/Vue devs fall for this too. querySelectorAll returns a 'NodeList'. It *looks* like an Array, and it has `forEach`, but it lacks `map` and `filter`. You have to evolve it into a real array first by writing `Array.from(nodeList)` or `[...nodeList]`.
① Read the explanation. Next: ② Do exercises.
You can make pages interactive with JS.
Next we'll learn modern layout techniques.