Đối tượng HTML trong DOM đại diện cho phần tử gốc <html> của tài liệu. Nó là phần tử cha của tất cả các phần tử khác trong trang.
Truy xuất đối tượng HTML
document.getElementsByTagName("HTML")[0]
Hoặc đơn giản hơn: document.documentElement
Ví dụ: Lấy toàn bộ nội dung HTML của trang
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: sans-serif; padding: 20px; }
.btn {
background-color: #17a2b8; color: white; border: none;
padding: 10px 20px; border-radius: 5px; cursor: pointer;
font-size: 1rem; margin: 10px; display: inline-block;
}
.show {
background: #f8f9fa; border: 2px solid #28a745;
padding: 15px; margin: 20px auto; max-width: 800px;
text-align: left; white-space: pre-wrap; font-family: monospace;
font-size: 0.85rem; overflow-x: auto; display: none;
}
</style>
</head>
<body>
<h1>Ví dụ DOM HTML Object</h1>
<button onclick="getContent()" class="btn">Lấy nội dung thẻ HTML</button>
<div id="output" class="show"></div>
<script>
function getContent() {
var htmlElement = document.documentElement; // hoặc document.getElementsByTagName("HTML")[0]
var content = htmlElement.outerHTML; // Lấy toàn bộ bao gồm thẻ html
document.getElementById("output").textContent = content;
document.getElementById("output").style.display = "block";
}
</script>
</body>
</html>
Kết quả
Trước khi nhấn nút:

Sau khi nhấn nút "Lấy nội dung thẻ HTML":

💡 Thực hành tốt: Dùng
document.documentElement thay vì getElementsByTagName("HTML")[0] vì ngắn gọn, hiệu năng tốt hơn và là tiêu chuẩn DOM Level 2.