หัวข้อ 1: Document Object Model และการเลือกอีลีเมนต์

คำจำกัดความ

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"]

DOM Tree: Parent, Child, Sibling

วิธีเลือก Element

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>

การ Traverse DOM

const current = document.querySelector("li");

// parentElement คือ element แม่
console.log(current.parentElement);

// children คือ element ลูกทั้งหมด
console.log(current.parentElement.children);

// nextElementSibling คือ element ถัดไปในระดับเดียวกัน
console.log(current.nextElementSibling);

สมการจำนวน Node ใน Tree อย่างง่าย

N = p + c + s

โดยที่ N คือจำนวน node ที่พิจารณา, p คือ parent node, c คือ child nodes, และ s คือ sibling nodes

แบบทดสอบหลังเรียน

  1. DOM คืออะไร
  2. querySelector() และ querySelectorAll() ต่างกันอย่างไร
  3. NodeList และ HTMLCollection ต่างกันอย่างไรในภาพรวม
  4. parentElement ใช้ทำอะไร
  5. ทำไม getElementById() จึงคืนค่าได้เพียง element เดียว

กลับสัปดาห์ที่ 5