What is JavaScript HTML DOM Document? Detail with examples and use cases.

The Document Object

When an HTML document is loaded into a web browser, it becomes a document object.

The document object is the root node of the HTML document.

The document object is a property of the window object.

The document object is accessed with:

window.document or just document

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.

With the object model, JavaScript gets all the power it needs to create dynamic HTML.

What is the HTML DOM?

  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements

The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.

  • Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
  • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
  • Form object − Everything enclosed in the <form>…</form> tags sets the form object.
  • Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.

Example

getElementById()

The following example changes the content (the innerHTML) of the <p> element with id="demo" :-

<html>
<body>

<p id=”demo”></p>

<script>
document.getElementById(“demo”).innerHTML = “Hello Roshan!”;
</script>

</body>
</html>

In the example above, getElementById is a method, while innerHTML is a property.

document.write()

<!DOCTYPE html>
<html>
<body>

<script>
document.write(Date());
</script>

</body>
</html>

document.querySelector()

<!DOCTYPE html>
<html>
<body>

<p>Add a background color to the first element with class=”example”: </p>

<script>
document.querySelector(“p”).style.backgroundColor = “red”;
</script>

</body>
</html>

The open() and close() Methods

<!DOCTYPE html>
<html>
<body>

<p>Add a background color to the first element with class=”example”: </p>

<button onclick = “myfunction()”>click me</button>

<script>
function myfuction() {

document.open();
document.write (“<h1> Hello Roshan </h1>”);

document.close();

}
</script>

</body>
</html>