The Document Object is one of the most fundamental concepts in JavaScript for interacting with and manipulating web pages. It represents the HTML document loaded into the browser and provides various methods and properties to dynamically alter the content, structure, and style of the page.
The document
object is a part of the Browser Object Model (BOM) and provides an interface to the HTML content of the webpage. It is the root node of the Document Object Model (DOM) hierarchy and allows developers to access, modify, and interact with the structure of a webpage.
Represents the entire webpage.
Allows access to elements like <div>
, <p>
, <a>
, etc.
Enables dynamic manipulation of the content, structure, and styling.
Document Object Example
Hello, World!
The document
object has several properties that provide details about the HTML document.
document.title: Gets or sets the title of the document.
console.log(document.title); // Outputs the title of the page
document.title = "New Title"; // Changes the title dynamically
document.URL: Returns the URL of the current document.
console.log(document.URL); // Outputs the current page URL
document.body: Refers to the <body>
element of the document.
console.log(document.body); // Outputs the body content
document.head: Refers to the <head>
element of the document.
console.log(document.head); // Outputs the head content
To interact with specific elements in the DOM, we use methods provided by the document
object.
document.getElementById() Retrieves an element by its id
.
Hello!
document.getElementsByClassName() Retrieves elements by their class name.
Box 1
Box 2
document.getElementsByTagName() Retrieves elements by their tag name.
- Item 1
- Item 2
document.querySelector() Retrieves the first element that matches a CSS selector.
Info 1
Info 2
document.querySelectorAll() Retrieves all elements that match a CSS selector.
Info 1
Info 2
Events allow interaction between the user and the webpage.
The document object is a powerful interface in JavaScript for interacting with the DOM. From selecting and modifying elements to handling events and styles, it enables developers to create dynamic and interactive web applications. By mastering the methods and properties of the document object, you can unlock the full potential of client-side web development. Happy coding !❤️