Dom Document in JavaScript
? DOM Document in JavaScript
What is the Document Object?
The document is the root of the DOM (Document Object Model) in a web page. It represents the entire HTML document and provides methods and properties to access, modify, and manipulate the page’s content.
Key Features of document
Access elements (
getElementById,querySelector, etc.)Create new elements (
createElement)Listen to events on the page
Get information about the page (title, URL, etc.)
Modify the HTML structure dynamically
Commonly Used document Methods and Properties
| Method / Property | Description | Example |
|---|---|---|
document.getElementById(id) | Get element by ID | document.getElementById("header") |
document.getElementsByClassName(className) | Get elements by class name | document.getElementsByClassName("item") |
document.querySelector(selector) | Get first element matching CSS selector | document.querySelector(".btn") |
document.querySelectorAll(selector) | Get all elements matching selector | document.querySelectorAll("p") |
document.createElement(tagName) | Create a new element | document.createElement("div") |
document.body | Get the <body> element | document.body.style.background = "yellow" |
document.title | Get or set the page title | document.title = "New Title" |
document.URL | Get the current page URL | console.log(document.URL) |
document.addEventListener(event, handler) | Attach event handler to the document | document.addEventListener("click", () => alert("Clicked!")) |
Example: Change the Page Title
console.log(document.title); // Current titledocument.title = "My New Page Title"; // Change title dynamicallyExample: Create and Insert a New Element
const newDiv = document.createElement("div");newDiv.textContent = "Hello, new div!";document.body.appendChild(newDiv);Example: Selecting and Changing Element Content
<p id="para">Original Text</p><script>const para = document.getElementById("para");para.textContent = "Text changed with JavaScript!";</script>Summary
documentis your gateway to interact with the entire webpage.You can select, create, modify, and listen to page elements using
document.It's the foundational object for DOM manipulation in JavaScript.
Would you like to see examples on event handling with document, or how to traverse the DOM tree?