คุณสมบัติ firstChild ใน HTML DOM ใช้สำหรับคืนค่าโหนดลูกแรก (first child node) ของโหนดที่ระบุ เป็นออบเจ็กต์ node อาจเป็น text node, element node, หรือ comment node ขึ้นอยู่กับโหนดใดอยู่ลำดับแรก เป็นคุณสมบัติแบบอ่านอย่างเดียว (read-only)
ไวยากรณ์ (Syntax)
node.firstChild
ตัวอย่าง
ตัวอย่างการดึงโหนดลูกแรกของ div (ไม่มี whitespace):
<!DOCTYPE html>
<html>
<head>
<script>
function getFirst() {
var childHTML = document.getElementById("DIV1").firstChild.innerHTML;
document.getElementById("Sample").innerHTML = "โหนดลูกแรกของ div คือ: " + childHTML;
}
</script>
</head>
<body>
<h1>คุณสมบัติ firstChild</h1>
<div id="DIV1"><p>This is a p element</p><span>This is a span element</span></div>
<button onclick="getFirst()">Get Child</button>
<p id="Sample"></p>
</body>
</html>
ผลลัพธ์
เมื่อโหลดหน้าเว็บจะแสดง div (เขียนต่อเนื่องไม่มีเว้นบรรทัด) มี p และ span ภายใน และปุ่ม "Get Child"
เมื่อคลิก "Get Child" จะแสดง "โหนดลูกแรกของ div คือ: This is a p element"
คำอธิบายโค้ด
- สร้าง
<div id="DIV1">เขียนติดกัน<p>...</p><span>...</span>ไม่มี whitespace - สร้างปุ่ม "Get Child" เรียกใช้
getFirst()เมื่อคลิก - ฟังก์ชัน
getFirst()ใช้firstChildของ div ได้<p>(เพราะไม่มี whitespace นำหน้า) - อ่าน
innerHTMLของ p แล้วแสดงในย่อหน้าid="Sample" - สำคัญ: หากมี whitespace (เว้นบรรทัด/เว้นวรรค) ระหว่าง
<div>และ<p>จะได้ text node แทน ซึ่งinnerHTMLจะเป็นundefined
ความแตกต่าง firstChild vs firstElementChild:firstChildนับทุกประเภทโหนด (รวม text, comment) ส่วนfirstElementChildนับเฉพาะ element node เท่านั้น