DOM can be called the structure of the document where the document can be an HTML webpage or an XML page. In this post, we are going to know what DOM is, how to work with live DOM viewers and how to access elements with a scripting language.
What is DOM?
DOM stands for document object model and is considered to be a standard for accessing, altering, and deleting elements from the document. This standard is set by the W3C (World Wide Web Consortium) and that is why DOM is most commonly referred to as the W3C DOM. The World Wide Web Consortium defined DOM as an interface that helps languages to interact with a document while staying language-neutral.
The Document in DOM stands for a document that can be an HTML document or an XML document. The Object in DOM is used to refer to elements or nodes of the document. While the Model in the DOM refers to the structure (or tree) of the document.
Also, the DOM acts like an application interface (API) for the scripting language to change elements of the HTML document
The structure of the document is somewhat like a tree. It contains the parent node and child nodes.
Working with live DOM viewers
Some websites provide us with live DOM generators, one of such live DOM viewers is provided on codepen.io. Consider,the following elements inside HTML webpage:
To generate the DOM hierarchy using the javascript code on code pen, Copy and paste these HTML elements inside DOM viewer on codepen.io
Below this HTML Tab on “codepen”, you’ll be able to see the DOM hierarchy like:
You can clearly see the parent nodes, child nodes and siblings nodes based on their indentation in the structure
Accessing HTML elements with JavaScript
JavaScript provides multiple methods to link the elements on an HTML webpage by interacting with the DOM. These methods are namely:
- getElementByID()
- getElementByClassName()
- getElementByName()
- getElementByTagName()
- getElementByTagNS()
To demonstrate this, create an HTML page with the following lines:
Add the link to the script file using the following line:
Inside the script file, add the following lines of code to change the background color of this p tag:
pTag.style.backgroundColor = "yellow";
You will get the following result on the browser:
There you go you have changed the style of an element using scripting language.
Conclusion
The DOM is set as a standard by W3C (World Wide Web Consortium) as an interface for the scripting language to interact with the elements of the document (HTML or XML). The scripting language (for example javascript) cannot directly access the elements of the webpage. Therefore, it interacts with the DOM and the DOM acts like an API and performs changes in the elements of the HTML webpage. The DOM structure is like a tree, having parent nodes, child nodes and sibling nodes.