JS DOM: Get document root / head / body

By Xah Lee. Date: .

Get root element, body element, document element

document.doctype

the Doctype.

// this is the DOCTYPE
console.log(document.doctype.nodeType === 10);
console.log(document.doctype.nodeName === "html");
console.log(document.doctype.nodeValue === null);
document.documentElement

the Root element. In html, it is the html tag.

/*
root element is  document.documentElement
in html, it is the html tag
*/
console.log(
 document.documentElement ===
  document.getElementsByTagName("html")[0],
);
// true

// this is the html tag, the root element
console.log(document.documentElement.nodeType === 1);
console.log(document.documentElement.nodeName === "HTML");
console.log(document.documentElement.nodeValue === null);
document.body

is the body tag.

/*
document.body is the body tag
*/
console.log(
 document.body ===
  document.getElementsByTagName("body")[0],
);
// true
document.head

is the head tag.

/*
document.head is the head tag
*/
console.log(
 document.head ===
  document.getElementsByTagName("head")[0],
);
// true