Object ใน Web Document จัดระเบียบในรูปแบบ Hierarchy (ลำดับชั้น) เริ่มจาก Window Object สูงสุด ลงมาจนถึง Form Control Elements
ลำดับชั้นของ Object (Object Hierarchy)
- Window Object - ระดับบนสุด (Top of Hierarchy) เป็น Global Object ใน Browser แทน Browser Window/Tab
- Document Object - แต่ละ HTML Document ที่โหลดใน Window จะกลายเป็น Document Object มีเนื้อหาของหน้าเว็บ
- Form Object - ทุกอย่างใน
<form>...</form>Tags - Form Control Elements - Elements ภายใน Form: Text Fields, Buttons, Radio Buttons, Checkboxes, Select, Textarea ฯลฯ
Hierarchy Diagram
รายละเอียดแต่ละระดับ
1. Window Object (Global Scope)
- Global Object ใน Browser
- Properties:
document,location,history,navigator,screen,localStorage,sessionStorage - Methods:
alert(),confirm(),prompt(),setTimeout(),setInterval(),fetch() - Global Variables/Functions กลายเป็น Properties ของ Window
2. Document Object (DOM Root)
- Root ของ DOM Tree
- Properties:
title,URL,domain,referrer,cookie,forms[],images[],links[] - Methods:
getElementById(),querySelector(),createElement(),write()
3. Form Object
- แทน
<form>Element - Properties:
action,method,elements[],name,target - Methods:
submit(),reset(),checkValidity()
4. Form Control Elements
<input>(text, password, checkbox, radio, file, hidden, submit, button, email, number, date, ...)<textarea>,<select>,<option>,<button>- Properties:
value,name,type,checked,selected,disabled,required - Methods:
focus(),blur(),select(),click()
การเข้าถึงใน Hierarchy
// Window Level
window.alert("Hello");
window.location.href = "...";
// Document Level
document.title = "New Title";
document.getElementById("myId");
document.forms[0]; // Form แรก
// Form Level
document.forms["loginForm"];
document.forms[0].elements["username"];
// Element Level
document.getElementById("username").value = "John";
document.querySelector("input[name='email']").value;
Modern DOM API (แนะนำ)
แทนที่จะเดิน Hierarchy แบบเก่า ใช้ Method ตรงๆ:
document.getElementById(id)document.querySelector(selector)document.querySelectorAll(selector)element.closest(selector)element.matches(selector)