JAVASCRIPT DOCUMENT OBJECT

Lavanya



JavaScript Document Object 

The document object represents the entire HTML document.

When an HTML document is loaded in the browser, it becomes a document object. This object serves as the root element representing the HTML document. It contains properties and methods, allowing us to add dynamic content to our web page.

As previously mentioned, it is an object of the window.

Window.document

Or

Window

As defined by the W3C, "The W3C Document Object Model (DOM) is a platform- and language-neutral interface that enables programs and scripts to dynamically access and modify a document's content, structure, and style."

Properties of document object 


Let's explore the properties of the document object that can be accessed and modified through it.




Methods of document object 


We can access and modify the contents of a document using its methods.

The key methods of the document object are as follows:



Accessing field value by document object 


In this example, we will retrieve the value of the text input provided by the user. We're using `document.form1.name.value` to access the value of the name field.

In this case, the document serves as the root element representing the HTML document.

form1 refers to the name of the form.

`name` is the attribute of the input text field.

`value`is the property that returns the content of the input text.

Example 


Let's look at a simple example of the document object that displays a welcome message with the name.

<script>


  // Get the current date and time
  var currentDate = new Date();
  
  // Get the current hour
  var hour = currentDate.getHours();
  
  // Set the welcome message based on the hour
  var welcomeMessage;
  if (hour < 12) {
    welcomeMessage = "Good Morning";
  } else if (hour < 18) {
    welcomeMessage = "Good Afternoon";
  } else {
    welcomeMessage = "Good Evening";
  }
  
  // Get the user's name
  var userName = prompt("Please enter your name:");
  
  // Write the welcome message to the document
  document.write("<h1>" + welcomeMessage + ", " + userName + "!</h1>");

</script>


Output:



Good Morning, John!


or


Good Afternoon, Jane!


or


Good Evening, Bob!


depending on the time of day and the user's input.















Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send