JavaScript Document Object Methods

The document object also provides various methods to access HTML elements. Here is the general form used to call a method:


List of Methods of Document Object

Here is the list of methods of document object in JavaScript:

  • open()
  • close()
  • write()
  • writeln()
  • getElementById()
  • getElementsByName()
  • getElementsByTagName()

JavaScript open() Method

The JavaScript open() method opens an HTML document to display the output. Here is the general form of open() method:, replace)

JavaScript close() Method

The JavaScript close() method closes an HTML document. Here is the general form of close() method:


JavaScript write() Method

The JavaScript write() method writes HTML expressions or JavaScript code into an HTML document. Here is the general form of the write() method:

document.write(exp1, exp2, ...)

JavaScript writeln() Method

The JavaScript writeln() method writes new line character after each HTML expressions or JavaScript code. Here is the general for of the writeln() method:

document.writeln(exp1, exp2, ...)

JavaScript getElementById() Method

The JavaScript getElementById() method returns the reference of first element of an HTML document with the specified id. Here is the general of the getElementById() method:


JavaScript getElementsByName() Method

The JavaScript getElementsByName() method returns the reference of an element with the specified name. Here is the general form of the getElementsByName() method:


JavaScript getElementsByTagName() Method

The JavaScript getElementsByTagName() method returns all the elements with the specified tagname. Here is the general form of the getElementsByTagName() method:


JavaScript Document Object Methods Example

Here is an example demonstrates document object methods in JavaScript:

   <title>JavaScript Document Object Methods</title>
   <script type="text/javascript">
      function getElement()
         new_window ="")
         var xyz = document.getElementsByName("ab")
         new_window.document.write("Length of Your Name is " + xyz.length)

<h3>JavaScript Document Object Methods Example</h3>
First Name:<input type="text" name="ab" size="20"><br/>
Middle Name:<input type="text" name="ab" size="20"><br/>
Last Name:<input type="text" name="ab" size="20"><br/>
<input type="button" onclick="getElement()" value="Calculate Length">


Here is the sample output of the above document object methods example in JavaScript. This is the initial output:

javascript document object methods

Now fill all the three fields and click on Calculate Length button as shown in the following figure:

document object methods

After clicking on the Calculate Length button, here is the output, you will see on your browser (in new window):

document object methods javascript

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube