Legacy DOM (DOM Level 0) เป็นรูปแบบเก่าสำหรับเข้าถึง Document Properties ผ่าน Collection ต่างๆ ของ Document Object รองรับโดย Browser ทุกตัว แต่เข้าถึงได้เฉพาะส่วนจำกัด (Forms, Images, Links, Anchors)
ตัวอย่างโค้ด
<html>
<head>
<title> Document Title </title>
<script>
function myFunc() {
var ret = document.title;
alert("Document Title : " + ret );
var ret = document.URL;
alert("Document URL : " + ret );
var ret = document.forms[0];
alert("Document First Form : " + ret );
var ret = document.forms[0].elements[1];
alert("Second element : " + ret );
}
</script>
</head>
<body>
<h1 id="title">This is main title</h1>
<p>Click the following to see the result:</p>
<form name="FirstForm">
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
<form name="SecondForm">
<input type="button" value="Don't ClickMe"/>
</form>
</body>
</html>
Legacy DOM Collections (Arrays-like)
| Collection | คำอธิบาย | ตัวอย่าง |
document.forms[] | Array ของ Form Elements | document.forms[0], document.forms["name"] |
document.images[] | Array ของ <img> Elements | document.images[0].src |
document.links[] | Array ของ <a href> Elements | document.links[0].href |
document.anchors[] | Array ของ <a name> Elements | document.anchors[0] |
document.applets[] | Array ของ <applet> (Deprecated) | - |
document.embeds[] | Array ของ <embed> Elements | document.embeds[0] |
Form Elements Access
// เข้าถึง Form
var form = document.forms[0]; // Index
var form = document.forms["formName"]; // Name Attribute
var form = document.formName; // Name Property (Legacy)
// เข้าถึง Elements ใน Form
form.elements[0]; // Index
form.elements["fieldName"]; // Name Attribute
form.fieldName; // Name Property (Legacy)
// Element Properties
element.value; // ค่า
element.type; // ชนิด
element.checked; // Checkbox/Radio
element.selected; // Option
element.disabled; // Disabled State
Legacy DOM Properties
| Property | คำอธิบาย |
document.title | Title ของหน้าเว็บ |
document.URL | URL ของหน้าเว็บ (Read-only) |
document.referrer | Referring Page URL |
document.domain | Domain (Security) |
document.cookie | Cookie String |
document.lastModified | Last Modified Date |
document.bgColor | Background Color (Deprecated) |
document.fgColor | Text Color (Deprecated) |
document.linkColor | Link Color (Deprecated) |
document.alinkColor | Active Link Color (Deprecated) |
document.vlinkColor | Visited Link Color (Deprecated) |
ข้อจำกัดของ Legacy DOM
- เข้าถึงได้เฉพาะ Forms, Images, Links, Anchors, Applets
- ไม่เข้าถึง Element ทั่วไปได้ (div, span, p, ฯลฯ)
- ไม่รองรับ Namespace / XML
- Collection เป็น Live (เปลี่ยนตาม DOM จริง)
Modern Alternative (W3C DOM)
// แทน document.forms[0].elements[1]
document.querySelector('form input:nth-child(2)');
document.getElementById('elementId');
document.getElementsByTagName('input');
document.getElementsByClassName('className');