Document Object: How to Control the DOM Root

The Document Object Model (DOM) is a way of representing and manipulating the content and structure of web documents. It provides an interface for programmers to access and modify the elements, attributes, text, and events of a document using JavaScript or other languages. The document object is the main entry point to the DOM, as it represents the entire document loaded in the browser. In this article, we will explore the document object and how to use it to control the root element of the DOM tree, which is the topmost element that contains all other elements in the document.

What is the document object?

The document object is a global object that is available in the browser's window object. It implements the Document interface, which defines a set of properties and methods for interacting with the DOM. Some of the most common properties and methods of the document object are:

  • document.createElement(tagName): Creates a new element with the given tag name and returns it.
  • document.createTextNode(data): Creates a new text node with the given data and returns it.
  • document.getElementById(id): Returns the element with the given id, or null if none is found.
  • document.getElementsByTagName(tagName): Returns a live HTMLCollection of elements with the given tag name.
  • document.getElementsByClassName(className): Returns a live HTMLCollection of elements with the given class name.
  • document.querySelector(selector): Returns the first element that matches the given CSS selector, or null if none is found.
  • document.querySelectorAll(selector): Returns a static NodeList of elements that match the given CSS selector.
  • document.write(html): Writes the given HTML string to the document.
  • document.open(): Opens the document for writing, replacing the existing content.
  • document.close(): Closes the document after writing, triggering the load event.
  • document.cookie: Gets or sets the cookie associated with the document.
  • document.title: Gets or sets the title of the document.
  • document.URL: Gets the URL of the document.
  • document.domain: Gets or sets the domain of the document.
  • document.readyState: Gets the current state of the document, such as "loading", "interactive", or "complete".
  • document.doctype: Gets the DocumentType object that represents the document type declaration.

The document object also inherits some properties and methods from the Node and EventTarget interfaces, such as:

  • document.nodeType: Gets the node type of the document, which is always 9 (DOCUMENT_NODE).
  • document.nodeName: Gets the node name of the document, which is always "#document".
  • document.nodeValue: Gets or sets the node value of the document, which is always null.
  • document.childNodes: Gets a live NodeList of the child nodes of the document.
  • document.firstChild: Gets the first child node of the document, or null if none exists.
  • document.lastChild: Gets the last child node of the document, or null if none exists.
  • document.parentNode: Gets the parent node of the document, which is always null.
  • document.nextSibling: Gets the next sibling node of the document, which is always null.
  • document.previousSibling: Gets the previous sibling node of the document, which is always null.
  • document.ownerDocument: Gets the document that owns the document, which is always null.
  • document.appendChild(child): Appends a new child node to the document.
  • document.removeChild(child): Removes a child node from the document.
  • document.replaceChild(newChild, oldChild): Replaces a child node with a new node in the document.
  • document.insertBefore(newChild, refChild): Inserts a new child node before a reference node in the document.
  • document.cloneNode(deep): Clones the document and returns the copy.
  • document.addEventListener(type, listener, options): Registers an event listener on the document.
  • document.removeEventListener(type, listener, options): Removes an event listener from the document.
  • document.dispatchEvent(event): Dispatches an event to the document.

How to access the root element of the DOM tree?

The root element of the DOM tree is the element that is the direct child of the document node. It is usually the <html> element in HTML documents, but it can also be a different element depending on the document type. For example, in XML documents, the root element can be any element defined by the XML schema.

To access the root element of the DOM tree, you can use the document.documentElement property. This property returns an Element object that represents the root element. For example, you can use the following code to get the root element and log its tag name to the console:

JAVASCRIPT
                        
// Get the root element
const root = document.documentElement;

// Log its tag name to the console
console.log(root.tagName); // "HTML"

You can also use the document.querySelector() method with the ":root" pseudo-class selector to get the root element. This selector matches the element that is the root of the document. For example, you can use the following code to get the root element and log its inner HTML to the console:

JAVASCRIPT
                        
// Get the root element using the :root selector
const root = document.querySelector(":root");

// Log its inner HTML to the console
console.log(root.innerHTML); // "<head>...</head><body>...</body>"

Why is it useful to control the root element of the DOM tree?

Controlling the root element of the DOM tree can be useful for various purposes, such as:

- Applying global styles or variables to the document using the root element's style or custom properties. For example, you can use the following code to set the font family and color of the document using the root element's style property:

JAVASCRIPT
                        
// Get the root element
const root = document.documentElement;

// Set the font family and color of the document
root.style.fontFamily = "Arial, sans-serif";
root.style.color = "blue";

Alternatively, you can use the following code to define and use custom properties on the root element:

JAVASCRIPT
                        
/* Define custom properties on the root element */
:root {
  --main-font: Arial, sans-serif;
  --main-color: blue;
}

/* Use custom properties in other selectors */
body {
  font-family: var(--main-font);
  color: var(--main-color);
}

- Accessing or modifying the attributes of the root element, such as lang, dir, or class. For example, you can use the following code to get and set the language and direction attributes of the root element:

JAVASCRIPT
                        
// Get the root element
const root = document.documentElement;

// Get the language and direction attributes of the root element
console.log(root.lang); // "en"
console.log(root.dir); // "ltr"

// Set the language and direction attributes of the root element
root.lang = "fr";
root.dir = "rtl";

- Adding or removing child nodes to the root element, such as <head>, <body>, or <script>. For example, you can use the following code to create and append a new script element to the root element:

JAVASCRIPT
                        
// Get the root element
const root = document.documentElement;

// Create a new script element
const script = document.createElement("script");

// Set the source attribute of the script element
script.src = "script.js";

// Append the script element to the root element
root.appendChild(script);

- Performing operations on the whole document using the root element's methods, such as root.cloneNode(), root.appendChild(), or root.removeChild(). For example, you can use the following code to clone the whole document and append it to the body element:

JAVASCRIPT
                        
// Get the root element
const root = document.documentElement;

// Clone the whole document
const clone = root.cloneNode(true);

// Append the clone to the body element
document.body.appendChild(clone);

Conclusion

In this article, we learned about the document object and how to use it to control the root element of the DOM tree. We saw that the document object is the main entry point to the DOM, and that the document.documentElement property or the document.querySelector(":root") method can be used to get the root element. We also discussed some of the benefits of controlling the root element, such as applying global styles, accessing or modifying attributes, or performing operations on the whole document. We hope that this article helped you understand the document object and how to use it to manipulate the DOM tree.