Property document.head ให้การเข้าถึง Element <head> ของเอกสารโดยตรง คืนค่า HTMLHeadElement Object
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head id="myid">
<title>JavaScript Example</title>
</head>
<body>
<h1>Employee Information</h1>
<form>
Name: <input type="text" name="name" value="Amit"><br>
Subject: <input type="text" name="sub" value="Java">
</form>
<script>
var a = document.head.id;
document.write("<br>Head element id? " + a);
</script>
</body>
</html>
คำอธิบาย
document.head— เข้าถึง<head>Element โดยตรง (รองรับ IE9+ และ Browser สมัยใหม่ทั้งหมด).id— ดึงค่า id attribute ของ head element- ผลลัพธ์:
Head element id? myid
การใช้งานที่พบบ่อย
- เพิ่ม/ลบ
<meta>,<link>,<style>,<script>แบบ Dynamic - อ่าน/แก้ไข
document.titleผ่านdocument.head.querySelector('title') - จัดการ CSP (Content Security Policy) Meta Tag
ตัวเลือกเก่า: document.getElementsByTagName('head')[0] — ใช้ได้กับ Browser เก่ามาก แต่ document.head สะดวกและทันสมัยกว่า