Level: Intermediate | player: 16_async_await
Learning Objectives
- Understand the concept of DOM tree.
- Select elements with
querySelector,querySelectorAll, andgetElementById. - Read properties as
getAttribute,dataset. - Know the difference between
textContentandinnerHTML(especially XSS). - Search for the Parent/Child/Sibling node.
1. What is DOM?
The browser parses HTML and creates a DOM (Document Object Model) tree. JavaScript reads and modifies this tree to change the screen.
2. Select element
const title = document.querySelector("#title"); //first matching
const items = document.querySelectorAll(".item"); // NodeList
const byId = document.getElementById("title");
querySelector accepts CSS selectors as is. querySelectorAll returns a static NodeList, so forEach is possible.
3. Attribute query
const link = document.querySelector("a");
link.getAttribute("href");
link.href; //DOM properties
link.dataset.userId; //data-user-id attribute
4. textContent vs innerHTML
textContent is safe because it is simple text and read/write. innerHTML parses HTML strings, so passing user input as is exposes it to XSS attacks. For external input, always use textContent or sanitize.
5. Tree navigation
el.parentElement;
el.children;
el.firstElementChild;
el.nextElementSibling;
Core example
| file | Contents covered |
|---|---|
| index.html | HTML page for example |
| 01_query_selector.js | Using querySelector/All |
| 02_attributes.js | getAttribute / dataset |
| 03_text_html.js | textContent vs innerHTML |
| 04_nested.js | Parent/Child/Sibling navigation |
⚠️ Common Mistakes
- Load the script from
<head>and access it while the DOM does not exist yet. - Mistake the
querySelectorAllresult as an array and call.mapdirectly (Array.from required). - Insert user input as is into
innerHTML. - Ignoring the subtle differences between
getAttribute("class")andel.className. - Depends on behavior when there are multiple elements with the same id.
❓ Frequently Asked Questions (FAQ)
Q1. Which is better, getElementById or querySelector("#id")? A. The performance difference is minimal. For consistency, you can just use querySelector.
Q2. Difference between NodeList and HTMLCollection? A. NodeList is static (or live), HTMLCollection is always live and does not have forEach.
Q3. Key name rules for dataset? A. data-user-id is converted to camel case to dataset.userId.