javascript
  1. javascript-document-object

JavaScript Document Object

The Document object in JavaScript represents the HTML document that is displayed in the browser. It provides a number of properties and methods for accessing and manipulating different parts of the document.

Syntax

To access the Document object in JavaScript, you can use the following syntax:

document

Example

Here is an example of accessing the Document object and changing the content of an HTML element:

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Document Object Example</title>
  </head>
  <body>
    <h1 id="title">Hello World</h1>
    <script>
      // Access the Document object and change the content of the h1 element
      document.getElementById("title").innerHTML = "Welcome!";
    </script>
  </body>
</html>

Output

The output of the above example will be the HTML page with the heading "Welcome!" instead of "Hello World".

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Document Object Example</title>
  </head>
  <body>
    <h1 id="title">Hello World</h1>
    <script>
      // Access the Document object and change the content of the h1 element
      document.getElementById("title").innerHTML = "Welcome!";
    </script>
  </body>
</html>

Try Playground

Explanation

In the example above, we first define an HTML document with a heading element that has an id of "title". We then use JavaScript to access the Document object and change the content of the heading element using the getElementById() method and the innerHTML property.

Use

The Document object is commonly used in JavaScript to:

  • Access and modify HTML elements
  • Create new HTML elements
  • Manipulate the document's history and URL
  • Get information about the user's browser and operating system

Important Points

  • The Document object is automatically created when the HTML document is loaded in the browser.
  • The Document object's properties and methods can be accessed and manipulated using JavaScript.
  • Some common properties of the Document object include title, body, and URL.

Summary

The Document object is an important part of JavaScript as it represents the HTML document that is displayed in the browser. It provides a number of properties and methods that allow developers to access and manipulate different parts of the document, such as HTML elements and the document's history. Understanding how to use the Document object can be useful for creating dynamic and interactive web pages.

Published on: