Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเขียนสคริปต์เข้าถึงคุณสมบัติเอกสารด้วย IE4 DOM Method

IE4 DOM (Document Object Model) ถูกนำเสนอใน Internet Explorer 4 เป็นโมเดล DOM แบบดั้งเดิม (Legacy) ก่อนมาตรฐาน W3C DOM IE 5+ รองรับ W3C DOM พื้นฐาน แต่ IE4 DOM ยังคงทำงานใน IE แบบเก่าและโหมด Compatibility

คุณสมบัติหลักของ IE4 DOM

  • document.all[] - คอลเลกชันของทุก Element ในเอกสาร (เข้าถึงได้ด้วย Index, ID, หรือ Name)
  • document.all.tags("tagName") - คอลเลกชัน Element ตาม Tag Name
  • document.all.idName - เข้าถึง Element ด้วย ID/Name โดยตรง
  • document.activeElement - Element ที่มี Focus อยู่
  • document.charset / defaultCharset - Character Set
  • document.children[] - Direct Children ของ Document (HTML Element เท่านั้น)
  • document.expando - อนุญาต/ห้ามการขยาย Property บน Object

ตัวอย่าง: เข้าถึง Heading และ Paragraph แรก

<html>
<head>
  <title>Document Title</title>
  <script>
    function myFunc() {
      // 1. เข้าถึง Element ด้วย ID ผ่าน document.all
      var heading = document.all["heading"]; // หรือ document.all.heading
      alert("Document Heading: " + heading.innerHTML);

      // 2. เข้าถึง Paragraph แรกด้วย tags()
      var paragraphs = document.all.tags("P");
      alert("First Paragraph: " + paragraphs[0].innerHTML);
    }
  </script>
</head>
<body>
  <h1 id="heading">This is main title</h1>
  <p>Click the following to see the result:</p>
  <form id="form1" 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>

ความแตกต่าง IE4 DOM vs W3C DOM

FeatureIE4 DOMW3C DOM (Standard)
Get by IDdocument.all["id"]document.getElementById("id")
Get by Tagdocument.all.tags("tag")document.getElementsByTagName("tag")
Get by Namedocument.all["name"]document.getElementsByName("name")
All Elementsdocument.alldocument.getElementsByTagName("*")
Active Elementdocument.activeElementdocument.activeElement (Standard ต่อมา)
Childrendocument.childrendocument.documentElement.children (html) / document.body.children

⚠️ ข้อควรระวัง

  • IE4 DOM ไม่ใช่มาตรฐาน ใช้ได้เฉพาะ IE (และ Edge Legacy) เท่านั้น
  • ไม่ควรใช้ในโครงการใหม่ ใช้ W3C DOM (getElementById, querySelector, getElementsByTagName) แทน
  • document.all ยังคงมีในเบราว์เซอร์สมัยใหม่เพื่อความเข้ากันได้ (Compatibility) แต่เป็น Legacy API
  • หากต้องรองรับ IE เก่า ให้ใช้ Polyfill หรือ Feature Detection: if (document.all && !document.getElementById) { ... }

สรุป

IE4 DOM ใช้ document.all และ document.all.tags() ในการเข้าถึง Element เป็นหลัก ปัจจุบันควรใช้ W3C DOM Standard Methods ทั้งหมดเพื่อความเข้ากันได้ข้ามเบราว์เซอร์