Document Object Model (DOM) is an essential part of the process of learning web development.
We use HTML to create the structure of the web application, use CSS to style that structure, and mostly use javascript for adding interactivity with the application. But JavaScript doesn’t understand the HTML tags or its syntax. So for example,
<body> <h1>Hello world!</h1> </body>
here javascript doesn’t understand the h1 tag or the body tag. So the question arises, how does javascript manipulate them or how does it access to these tags? Well, this is where the DOM comes in handy. Document Object Model or the DOM is the HTML document presented in object format Where the “Document” object is at the top of this hierarchical tree followed by “HTML” which is the root object, and going so on. The following image represents the DOM hierarchy properly.
As you can see the document object has the highest position in this hierarchy. So whenever we use javascript to access a certain type of element like h1 it uses this tree-like structure to find them and using this hierarchy we can access every HTML element through javascript. With this knowledge we can do all sorts of things, dynamically changing the content in our application, creating and deleting elements using parent and child relations, handling HTML forms, and many more. Many people use the “document” object without really knowing how and why. So having a clear picture of this hierarchical tree helps anyone to better understand the DOM and have a good flow in their program. Also, debugging becomes a lot easier.
In the following code,
const element1 = document.getElementById("Box");
we have declared a constant named element1 which has been given the value of an object with the id “box” from the HTML document. So the element inside the document model with the id of “Box” is an object in javascript and here element1 holds the value of that object.
DOM has a lot of things to talk about but this was just an introduction to what a DOM is. Always remember that there is always more to learn.