[JavaScript] document Object

The “document” property of the “window” object returns the document object, which represents a web page or a document. The “document” object provides access to all HTML elements in a page.


1. Properties

You can access the information about the document using the following properties:

  • URL : the URL of the current page
  • title : the title of the current page
  • cookie : the cookie data
  • lastModified : the last modified date
  • referrer : the previous page with a link to the current page

Also you can access elements in the documents.

  • images[] : a collection of all images used in the document
  • anchors[] : a collection of all anchors
  • links[] : a collection of all links
  • forms[] : a collection of all forms


2. Getting Document Information

The following code retrieves the information about the page through the “document” object.

console.log("URL: " + window.document.URL);
console.log("Title: " + document.title);
console.log("Last Modified: " + window.document.lastModified);


3. Writing Text in a Document

The “document” object provides the “write()” method to write text directly to the page.

  • document.write()
  • document.writeln() : add a new line character (\n) at the end

The “write()” method is used within a <script> tag in the body of an HTML document.

  Last Modified :

The use of the “write()” method is discouraged. You can use the DOM access methods to write text in the document.


4. Links and Anchors

We have the following links.

<a href="a1.html" id="a1" alt="a1">Anchor 1</a>
<a href="a2.html" id="a2" alt="a2">Anchor 2</a>
<map name="mymap">
  <area shape="rect" coords="0,0,100,120" href="#" alt="area1" />
  <area shape="circle" coords="100,50,10" href="#" alt="area2" />
  <area shape="circle" coords="200,50,10" href="#" alt="area3" />

How many links and anchors are there? Can you guess?


There are 2 anchors and 5 links. The link collection counts <a> and <area> tags.


5. Images

<img id="Img1" src="images/big.png" alt="Image1" />
<img id="Img2" src="images/small.png" alt="Image2" />

You can iterate all images through “document.images” property.

for (i = 0; i < document.images.length; i++)
  console.log(document.images[i].id + ", src=" + document.images[i].src);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s