Document Object in JavaScript

The Document Object in JavaScript represents the web page that is loaded into the browser. It is part of the Window interface and provides properties, methods, and events to interact with the document's content, structure, and appearance. Using the Document Object, developers can dynamically manipulate the content and layout of a web page.

Key Features of the Document Object:

Common Properties and Methods of the Document Object:

Example: Accessing Document Properties

The following code example shows how to retrieve and display various properties of the document using JavaScript:

Example


document.write("Document Title: " + document.title + "<br>");
document.write("Document URL: " + document.URL + "<br>");
document.write("Document Last Modified: " + document.lastModified + "<br>");
document.write("Document Domain: " + document.domain + "<br>");

Output

Document Title: My Website
Document URL: https://example.com
Document Last Modified: 11/15/2024 12:34 PM
Document Domain: example.com

Explanation of Code:

Additional Code Example 1: Changing Content Dynamically

This example demonstrates how to change the content of an HTML element using the Document Object:

Example


document.getElementById("demo").innerHTML = "New Content";

Output

Content of the element with ID "demo" changes to "New Content".

Additional Code Example 2: Creating and Adding Elements

In this example, a new paragraph element is created and appended to the body of the document:

Example


var para = document.createElement("p");
para.innerHTML = "This is a new paragraph.";
document.body.appendChild(para);

Output

A new paragraph saying "This is a new paragraph." is added to the page.

Additional Code Example 3: Changing Element Styles

This example demonstrates how to change the style of an element using the Document Object:

Example


document.getElementById("demo").style.color = "blue";
document.getElementById("demo").style.fontSize = "20px";

Output

The color of the text in the element with ID "demo" changes to blue, and the font size is increased to 20px.

Additional Code Example 4: Using querySelector and Modifying Attributes

This example demonstrates selecting an element using querySelector and modifying its attribute:

Attribute Modification Example


document.querySelector("img").setAttribute("src", "new_image.jpg");

Output

The source of the first image element on the page changes to "new_image.jpg".