DOM Document

The document object is the entry point to the DOM and represents the entire HTML or XML document. It provides methods and properties to access, manipulate, and query the structure of the document.

Key Topics

Document Overview

The document object provides a way to programmatically interact with the content and structure of a webpage. It represents the root of the DOM tree.

Querying Elements

You can use document methods like getElementById, querySelector, and getElementsByClassName to locate elements in the document.

const element = document.querySelector("#demo");
console.log(element.textContent);

Output

> Logs the text content of the element with id "demo".

Explanation: The querySelector method retrieves the first element that matches the specified CSS selector.

Document Properties

The document object has various properties like title, URL, and body to access and modify the document's metadata and content.

console.log(document.title);
document.title = "New Document Title";
console.log(document.body.innerHTML);

Output

> Logs the current document title.

> Updates and logs the new document title.

> Logs the inner HTML content of the body element.

Explanation: The title property gets or sets the document's title, and the body property provides access to the body element's content.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating the usage of the document object to modify the webpage dynamically.

<!DOCTYPE html>
<html>
    <head>
        <title>DOM Document Example</title>
    </head>
    <body>
        <h1 id="demo">Original Title</h1>
        <button onclick="updateDocument()">Update Document</button>

        <script>
            function updateDocument() {
                document.title = "Updated Title";
                const element = document.getElementById("demo");
                element.textContent = "Updated Heading";
            }
        </script>
    </body>
</html>

Key Takeaways

  • Document Object: Acts as the entry point to the DOM.
  • Querying Elements: Use methods like getElementById and querySelector for element selection.
  • Properties: Access and modify metadata and content using properties like title and body.
  • Dynamic Updates: Modify the document dynamically to create responsive webpages.