JavaScript Document Object Model (DOM) คือการแสดงภาพของ HTML elements ของเว็บเพจ เป็น interface ที่ใช้จัดการเว็บเพจโดยเปลี่ยนเนื้อหาหรือสไตล์
เข้าถึง DOM ได้โดยคลิกขวาที่เว็บเพจ → Inspect จะเห็น HTML elements ด้านขวา/ซ้าย Hover ที่ element จะเห็นส่วนของหน้าเว็บที่ element นั้นแทนไฮไลท์
สามารถจัดการเนื้อหาหรือสไตล์ผ่าน console ได้
DOM เป็นโครงสร้างข้อมูลแบบต้นไม้ (tree) มี parent และ nested children Elements ที่ไม่มี children เรียกว่า "leaves" ตัวอย่างโครงสร้าง: document → html → head (scripts, title) และ body (แยก branch)
การเลือก Elements ใน DOM
มี 2 วิธีหลัก:
- getElements methods
- querySelector methods
getElement Methods
รับ argument เดียว: tag name, class name, หรือ id
document.getElementsByTagName('p')- คืน HTMLCollection (array-like) บอกจำนวน p tagsdocument.getElementsByClassName('classname')- คืน HTMLCollection ของ elements ที่มี class นั้นdocument.getElementById('idname')- คืน element เดียว (id ควร unique)
querySelector Methods
ต้องใส่ . หน้า class name และ # หน้า id name
document.querySelector('selector')- คืน element แรกที่ matchdocument.querySelectorAll('selector')- คืน NodeList (array-like) ใช้.forEach()ได้
ความแตกต่าง: HTMLCollection ไม่มี forEach() แต่ NodeList มี แปลงเป็น Array จริงได้ด้วย Array.from(arrayLikeObject)
สรุป
DOM เป็น interface อันทรงพลัง แสดง HTML ของเว็บเพจ โครงสร้างแบบต้นไม้ ใช้ querySelector() หรือ getMethods เพื่อเลือก elements แล้วจัดการด้วย JavaScript