The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.
A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The Document Object Model (DOM) represents that same document so it can be manipulated. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.
Simple example of using DOM / Document is as below,
<html>
<head>
<script>
// run this function when the document is loaded
window.onload = function() {
// create a couple of elements in an otherwise empty HTML page
const heading = document.createElement("h1");
const heading_text = document.createTextNode("Lynxbee DOM TEST page!");
heading.appendChild(heading_text);
document.body.appendChild(heading);
}
</script>
</head>
<body>
</body>
</html>
If you try html is browser, you will see “Lynxbee DOM Test page!” printed in browser page. But as you can see above, we don’t have any actual HTML code written but the text has been printed from JAVAScript .. so altimately JAVAScript created html element h1 and added text in the h1 html tag.
The same code can also be implemented as,
<html>
<head>
<script>
window.onload = function() {
var htmlElement = document.getElementById("h1ElementId");
htmlElement.innerHTML = "Lynxbee DOM TEST page!";
}
</script>
</head>
<body>
<h1 id="h1ElementId"></h1>
</body>
</html>
As we can see above, we written an HTML code with h1 tag and set an ID to it as “h1ElementId” and accessed this html element inside javascript to change the contents of the h1 element / tag using javascript function.
So, you must have understood so far that, whatever we write inside “body” tag, can be called as document as mentioned earlier “A Web page is a document. This document can be either displayed in the browser window or as the HTML source.”
Reference :