⚡ Module 16 · JS Integration🟡 IntermediateLESSON 56
DOM Interaction
Course progress78%
🎯 What you'll learn: Selecting elements with
getElementById/querySelector, changing content with innerHTML/textContent, and building new elements with createElement.
Section 1
Selecting Elements
The DOM (Document Object Model) is JavaScript's live representation of your HTML — a tree of objects you can read and modify. querySelector is the modern, flexible choice since it accepts any CSS selector.
dom-select.html
HTML
<script> const byId = document.getElementById('title'); // one element by id const first = document.querySelector('.card'); // first match const all = document.querySelectorAll('.card'); // NodeList of all matches </script>
| Method | Returns |
|---|---|
| getElementById('x') | Single element, or null |
| querySelector('.x') | First matching element, or null |
| querySelectorAll('.x') | A NodeList of all matches |
Section 2
innerHTML vs textContent
innerHTML parses its input as HTML — useful for inserting markup, but risky with untrusted input. textContent treats input as plain text, escaping anything that looks like a tag — always the safer choice for user-supplied content.
dom-content.html
HTML
<script> el.innerHTML = '<strong>Bold text</strong>'; // renders as bold el.textContent = '<strong>Bold text</strong>'; // shows the literal tags as text </script>
⚠️
Never put untrusted input into innerHTML
Setting innerHTML from user-provided text is a classic XSS vulnerability — a malicious <script> tag in that string would execute. Use textContent for anything not fully trusted.
Section 3
Creating & Appending Elements
dom-create.html
HTML
<script> const li = document.createElement('li'); li.textContent = 'New list item'; document.querySelector('ul').appendChild(li); </script>
🧩 Knowledge Check — Lesson 56
5 questions to test your understanding.
1. What does querySelectorAll return?
2. What's the key risk of setting innerHTML from untrusted input?
3. What does textContent do with a string like "<b>hi</b>"?
4. How do you add a newly created element to the page?
5. What does getElementById return if no element has that id?
Coding Challenge — Lesson 56
Apply what you learned · Intermediate Level
Challenge: Build a Dynamic List Adder
Write JS that creates a new <li> element with textContent "Item added dynamically" and appends it to an existing <ul id="myList">.
Write JS that creates a new <li> element with textContent "Item added dynamically" and appends it to an existing <ul id="myList">.
💡 Show hints if you're stuck
- createElement → set textContent → appendChild, in that order.
Finished this lesson?
Mark it complete to track your progress.
Lesson 56 of 62Module 16 — HTML + JavaScript