Skip to content

Document object in JavaScript

  • by

JavaScript document object represents the whole html document. Once an HTML document is loaded into a web browser, it becomes a document object.

window.document  
//OR
document  

This is a root element of the HTML document that represents the html document. You can access document objects with a window or without a window.

Methods of the document object

Some of the commonly used methods of the document object:

MethodDescription
write(“string”)writes the given string on the doucment.
writeln(“string”)writes the given string on the doucment with newline character at the end.
getElementById()returns the element having the given id value.
getElementsByName()returns all the elements having the given name value.
getElementsByTagName()returns all the elements having the given tag name.
getElementsByClassName()returns all the elements having the given class name.
open()opens an HTML document to display the output
close()closes an HTML document

Document Object Properties

A property of an object is the value associated with the object. The property is accessed by using the following notation:

objectName.propertyName
PropertiesDescription
cookiereturns a report that contains all the visible and unexpired cookies associated with the document
domainreturns the domain name of the server from which the document has originated
lastModifiedreturns the date on which document was last modified
documentModereturns the mode used by the browser to process the document
readyStatereturns the loading status of the document.
referrerreturns the URL of the documents referred to in an HTML document
titlereturns the name of the HTML document defined between the starting and ending tags of the TITLE element
URLreturns the full URL of the HTML document.

Document object in JavaScript

Simple example code document object properties in action.

<!DOCTYPE html>
<html>
<head>
  <body>

   <script>
    console.log(document.domain )
    console.log(document.lastModified )
    console.log(document.documentMode )
    console.log(document.title )
    console.log(document.url )
  </script>

</body>
</html>

Output:

Document object in JavaScript

Another example, is to see the document object methods like open(), write(), and getElementById() to explain their usage.

<!doctype html>
<html>

	<body>
		<h3>Document Methods Example</h3>
		<p id="demo">It Will change</p>

		<script>
		    // Open document
		    document.open();
		    // writing
			document.write("Hello" +"<br>");
			document.getElementById("demo").innerHTML = "Set by ID";
		</script>
	</body>
</html>

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *