The Document interface, mentioned above, represents any web page loaded in the browser. It serves as an entry point into the web page’s content, which is the DOM tree. It also describes the common properties and methods for any kind of document.
Don't become Obsolete & get a Pink Slip
Follow DataFlair on Google News & Stay ahead of the game
A Document Object Model is a programming interface for HTML (HyperText Markup Language) and XML (eXtensible Markup Language) documents. It provides a data representation comprising all the objects, depicting the structure and content of the document on the web. Every webpage has its own DOM that represents the page so that programs can alter its structure, look, and content.
- Creation of the DOM tree
- Manipulation of the DOM tree
<html> <head> <title>DOM Model</title> </head> <body> <h1>DataFlair’s Tutorial</h1> <p>DOM Tree</p> <p id = "text">This is a text element in the DOM tree.</p> </body> </html>
The diagram below depicts the DOM tree of the document.
Every element, attribute, and text content in the HTML creates its own DOM node in the tree. A DOM tree consists of four main types of nodes:
This is added at the top of the tree and represents the entire page in the browser. As stated above, it is the starting point in the DOM tree; you need to navigate via the document node to access any other node in your DOM tree.
All the HTML elements like heading tags (<h1> to <h6>) and paragraph tags (<p>) in the page create an element node in the tree. You use these nodes to gain access to the elements’ attribute and text nodes.
When the opening tags in the HTML document contain attributes, the tree represents them as attribute nodes. These are not the children of the element nodes but a part of them.
Once you have access to the element node, you can reach the text content within that element, stored inside the text nodes of the DOM tree. These nodes cannot have child nodes. Thus, a text node always creates a new branch in the DOM tree, and no further branches come out of it.
Let’s see how our code above turned out into the browser window and how the DOM tree helps us in manipulating webpages very easily.
In the above image, I hovered over <h1> tag in the Elements Tab. On the left, notice how the browser highlighted the tag that I selected. It also shows the attribute you choose in your code on your browser window. When you right-click on your node, the browser provides you with the option to add/ remove an element directly without going to the source file. It also provides a live preview of what changes happened in the webpage when you altered the code.
To access and modify the DOM tree, you need to follow two steps:
- Locate the node representing the element you want.
- Works with the node’s content, child elements, and attributes.
This is only an overview of all the methods and properties that you will learn further in this tutorial. It acts as a guide when you search for a specific topic in the future. All the methods mentioned are detailed as you continue reading the tutorial, so you will have a strong understanding of all of them when you finish this tutorial. Some DOM methods only work in certain browsers or are buggy. Inconsistent browser support for the DOM was one of the reasons jQuery became popular.
We will discuss the various properties and methods in this tutorial based on the DOM tree given below.
Accessing the Elements
DOM Queries are the methods that find elements in the DOM tree. They may return one element or a collection of elements in a NodeList. You can select any element you desire from the NodeList with the help of an index number (starting with 0).
Methods to Select an Individual Element Node
Following are the methods to select an individual element in the tree:
- getElementById(‘id’): Uses the unique value of the element’s id attribute. The HTML must have an id attribute for the method to select it.
For example – getElementById(‘one’)
- querySelector(‘css selector’): Uses a CSS selector, returns the first matching element.
For example – querySelector(‘h1’)
The code below combines these methods to add styling to the webpage.
Methods to Select Multiple Elements (NodeLists)
There are three common ways to select multiple elements in the tree:
- getElementsByClassName(): Selects all the elements that have a specified value for the class attribute.
For example – getElementsByClassName(‘mandatory’)
- getElementsByTagName(): Selects all the elements that have the specified tag names.
For example – getElementsByTagName(‘h1’)
- querySelectorAll(): Uses a CSS selector, returns all the matching elements.
For example – querySelectorAll(‘li.mandatory’)
The above methods always return a NodeList, even if the list contains only a single element. This fact is important to remember because you need to use square brackets [ ] if you want to access any element in the NodeList. The following code explains all the methods of returning a NodeList.
Traversing between Element Nodes
You have the facility to navigate between related element nodes. The techniques available for this purpose include:
- parentNode: Selects the parent of the current element node (returns a single element).
- previousSibling/ nextSibling: Selects the previous or next sibling from the tree.
- firstChild/ lastChild: Selects the first or last child of the current element.
Thus, it is important to strip whitespaces, making the code smaller and faster to read. But this results in a code that is difficult to read. To avoid this, we use jQuery for traversing of DOM.
Get/ update Element Content
For Text only
You can access and update the text in the containing element (and its children) with the help of two properties:
For example – document.getElementById(‘p’).textContent; (accessing)
document.getElementById(‘p1’).textContent = newText; (updating)
For example – document.getElementById(‘p’).innerText; (accessing)
document.getElementById(‘p2’).innerText = newText; (updating)
Both these properties replace the entire content of the element, including all the markup present. But you should avoid using innerText since it is not part of any standard. Also, this method slows the speed of content loading on the page.
For Text and Markup
The innerHTML property gets the content of the element and returns it as one long string, including the markup it contains. But you should be careful of where you use this property since there are some security risks associated with it.
For example – document.getElementById(‘p’).innerHTML; (accessing)
document.getElementById(‘p3’).innerHTML = newText; (updating)
The code below shows the three properties clearly. Run the code on your browser, and see the output on your own. Play with the code, try adding and removing things, and see what happens. This will help you understand how these properties work.
Adding/ removing HTML Content
In the above example, we added an HTML <strong> tag in the page with the help of innerHTML property. To remove any text content, all you need to do is store an empty string in the element.
document.getElementById(‘p3’).innerHTML = “ ”; (empty string)
This will remove the text nodes of the containing and its child elements from the HTML content.
Another technique to add/remove HTML content is DOM Manipulation. To add HTML content to your webpage, you need to follow the three steps discussed below:
- Create a new element using createElement().
- Give it content by creating a text node using createTextNode() and adding it to the element using the appendChild() method.
- Add the element to the DOM tree by finding the location and then using appendChild().
To remove an element from the webpage, the steps are as follows:
- Store the element you want to remove in a variable.
- Store the parent of that element in another variable.
- Remove the element from its containing element using the removeChild() method.
If you have an element, you can easily access its attributes and update them if you wish to. You can do this in two simple steps as shown below:
- Select the element node that carries the attribute you want to access, followed by a period symbol.
- Use one of the methods or properties to work with the attribute.
Hope you liked our article. Still, having queries? Let us know through the comment section.