Property document.documentElement คืนค่า Root Element ของเอกสาร HTML ซึ่งคือ <html> Element (NodeName = "HTML")
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<p>Demo Text</p>
<script>
document.body.style.backgroundColor = "gray";
var a = document.documentElement.nodeName;
document.write("Node Name: " + a); // ผลลัพธ์: "HTML"
</script>
</body>
</html>
คำอธิบาย
document.documentElement— Root Element (<html>).nodeName— ชื่อโหนด ตัวพิมพ์ใหญ่เสมอสำหรับ HTML Elements- ต่างจาก
document.bodyที่เป็น<body>Element
การใช้งานที่พบบ่อย
- ตั้งค่า CSS Variable บน
:rootผ่านdocument.documentElement.style.setProperty('--var', 'value') - คำนวณ Viewport Size:
document.documentElement.clientWidth/Height - Scroll Position:
document.documentElement.scrollTop(ในบาง Mode) - Language Attribute:
document.documentElement.lang