DOM (Document Object Model) คือโครงสร้างแบบ tree ที่ browser สร้างจาก HTML เพื่อให้ JavaScript เข้าถึง อ่าน และแก้ไขหน้าเว็บได้
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart TD
A["document
เอกสารหลัก"] --> B["html
Root element"]
B --> C["head
ข้อมูลเอกสาร"]
B --> D["body
เนื้อหาหน้าเว็บ"]
D --> E["header
Parent node"]
D --> F["main
Sibling node"]
F --> G["section
Child node"]
G --> H["p
Text content"]
| Method | คืนค่า | เหมาะกับ |
|---|---|---|
getElementById() |
Element หรือ null |
เลือกด้วย id |
querySelector() |
Element แรกหรือ null |
เลือกด้วย CSS selector |
querySelectorAll() |
NodeList | เลือกหลาย element |
getElementsByClassName() |
HTMLCollection | เลือกด้วย class |
getElementsByTagName() |
HTMLCollection | เลือกด้วย tag |
<main id="app">
<h1 class="title">DOM Lesson</h1>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</main>
<script>
// เลือก element ด้วย id
const app = document.getElementById("app");
// เลือก element แรกด้วย CSS selector
const title = document.querySelector(".title");
// เลือก li ทุกตัว คืนค่าเป็น NodeList
const items = document.querySelectorAll("li");
// แสดงผลลัพธ์การใช้งาน
console.log(app);
console.log(title.textContent);
items.forEach(item => console.log(item.textContent));
</script>
const current = document.querySelector("li");
// parentElement คือ element แม่
console.log(current.parentElement);
// children คือ element ลูกทั้งหมด
console.log(current.parentElement.children);
// nextElementSibling คือ element ถัดไปในระดับเดียวกัน
console.log(current.nextElementSibling);
โดยที่ N คือจำนวน node ที่พิจารณา, p คือ parent node, c คือ child nodes, และ s คือ sibling nodes
querySelector() และ querySelectorAll() ต่างกันอย่างไรparentElement ใช้ทำอะไรgetElementById() จึงคืนค่าได้เพียง element เดียว