The Wayback Machine - https://web.archive.org/web/20241010122214/https://www.geeksforgeeks.org/dom-document-object-model/
Open In App

HTML DOM (Document Object Model)

Last Updated : 14 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

HTML DOM (Document Object Model) is a hierarchical representation of HTML documents. It defines the structure and properties of elements on a webpage, enabling JavaScript to dynamically access, manipulate, and update content, enhancing interactivity and functionality.

Note: It is called a Logical structure because DOM doesn’t specify any relationship between objects. 

What is DOM?

DOM, or Document Object Model, is a programming interface that represents structured documents like HTML and XML as a tree of objects. It defines how to access, manipulate, and modify document elements using scripting languages like JavaScript.

So basically Document Object Model is an API that represents and interacts with HTML or XML documents.

The DOM is a W3C (World Wide Web Consortium) standard and it defines a standard for accessing documents.

The W3C Dom standard is divided into three different parts:

  • Core DOM – standard model for all document types
  • XML DOM – standard model for XML documents
  • HTML DOM – standard model for HTML documents

HTML DOM

HTML DOM is a standard object model and programming interface for HTML documents. HTML DOM is a way to represent the webpage in a structured hierarchical way so that it will become easier for programmers and users to glide through the document.

With HTML DOM, we can easily access and manipulate tags, IDs, classes, attributes, or elements of HTML using commands or methods provided by the document object.

Using DOM JavaScript we get access to HTML as well as CSS of the web page and can also modify the behavior of the HTML elements.

Why is DOM Required?

HTML is used to structure the web pages and Javascript is used to add behavior to our web pages. When an HTML file is loaded into the browser, the JavaScript can not understand the HTML document directly. So it interprets and interacts with the Document Object Model (DOM), which is created by the browser based on the HTML document.

DOM is basically the representation of the same HTML document but in a tree-like structure composed of objects. JavaScript can not understand the tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM.

JavaScript interprets DOM easily, using it as a bridge to access and manipulate the elements. DOM Javascript allow access to each of the objects (h1, p, etc) by using different functions.

The Document Object Model (DOM) is essential in web development for several reasons:

  • Dynamic Web Pages: It allows you to create dynamic web pages. It enables the JavaScript to access and manipulate page content, structure, and style dynamically which gives interactive and responsive web experiences, such as updating content without reloading the entire page or responding to user actions instantly.
  • Interactivity: With the DOM, you can respond to user actions (like clicks, inputs, or scrolls) and modify the web page accordingly.
  • Content Updates: When you want to update the content without refreshing the entire page, the DOM enables targeted changes making the web applications more efficient and user-friendly.
  • Cross-Browser Compatibility: Different browsers may render HTML and CSS in different ways. The DOM provides a standardized way to interact with page elements.
  • Single-Page Applications (SPAs): Applications built with frameworks such as React or Angular, heavily rely on the DOM for efficient rendering and updating of content within a single HTML page without reloading the full page.

Structure of DOM

DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is sometimes used to describe the tree-like representation of a document.  

Each branch of the tree ends in a node, and each node contains objects  Event listeners can be added to nodes and triggered on an occurrence of a given event. One important property of DOM structure models is structural isomorphism: if any two DOM implementations are used to create a representation of the same document, they will create the same structure model, with precisely the same objects and relationships.

Why DOM is called an Object Model?

Documents are modeled using objects, and the model includes not only the structure of a document but also the behavior of a document and the objects of which it is composed like tag elements with attributes in HTML.

Properties of DOM

Let’s see the properties of the document object that can be accessed and modified by the document object.

properties of DOM flowchart

Representation of the DOM

  • Window Object: Window Object is object of the browser which is always at top of the hierarchy.  It is like an API that is used to set and access all the properties and methods of the browser. It is automatically created by the browser.
  • Document object: When an HTML document is loaded into a window, it becomes a document object. The ‘document’ object has various properties that refer to other objects which allow access to and modification of the content of the web page. If there is a need to access any element in an HTML page, we always start with accessing the ‘document’ object. Document object is property of window object.
  • Form Object: It is represented by form tags.
  • Link Object: It is represented by link tags.
  • Anchor Object: It is represented by a href tags.
  • Form Control Elements: Form can have many control elements such as text fields, buttons, radio buttons, checkboxes, etc.

Methods of Document Object

DOM provides various methods that allows users to interact with and manipulate the document. Some commonly used DOM methods are:

MethodDescription
write(“string”)Writes the given string on the document.
getElementById()Returns the element having the given id value.
getElementsByName()Returns all the elements having the given name value.
getElementsByTagName()Returns all the elements having the given tag name.
getElementsByClassName()Returns all the elements having the given class name.

Example: In this example, We use HTML element id to find the DOM HTML element.

HTML
<!DOCTYPE html>
<html>

<body>
    <h2>GeeksforGeeks</h2>

    <!-- Finding the HTML Elements by their Id in DOM -->
    <p id="intro">
        A Computer Science portal for geeks.
    </p>
    <p>
        This example illustrates the <b>getElementById</b> method.
    </p>
    <p id="demo"></p>
    <script>
        const element = document.getElementById("intro");
        document.getElementById("demo").innerHTML =
            "GeeksforGeeks introduction is: " + element.innerHTML;
    </script>
</body>

</html>

Output:

getelementbyid() method example output

Getting the HTML element by getElementById() Method

Example : This example describes the representation of the HTML elements in the tree structure.

html
<table>
    <ROWS>
        <tr>
            <td>Car</td>
            <td>Scooter</td>
        </tr>
        <tr>
            <td>MotorBike</td>
            <td>Bus</td>
        </tr>
    </ROWS>
</table>
html elements in tree-like structure

HTML elements in tree-like structure

What DOM is not? 

  • The Document Object Model is not a binary description where it does not define any binary source code in its interfaces.
  • The Document Object Model is not used to describe objects in XML or HTML whereas the DOM describes XML and HTML documents as objects.
  • The Document Object Model is not represented by a set of data structures; it is an interface that specifies object representation.
  • The Document Object Model does not show the criticality of objects in documents i.e it doesn’t have information about which object in the document is appropriate to the context and which is not.

Levels of DOM

DOM consisted of multiple levels, each representing different aspect of the document.

  • Level 0: Provides a low-level set of interfaces.
  • Level 1: DOM level 1 can be described in two parts: CORE and HTML.
    • CORE provides low-level interfaces that can be used to represent any structured document.
    • HTML provides high-level interfaces that can be used to represent HTML documents.
  • Level 2: consists of six specifications: CORE2, VIEWS, EVENTS, STYLE, TRAVERSAL, and RANGE.
    • CORE2: extends the functionality of CORE specified by DOM level 1.
    • VIEWS: views allows programs to dynamically access and manipulate the content of the document.
    • EVENTS: Events are scripts that are either executed by the browser when the user reacts to the web page.
    • STYLE: allows programs to dynamically access and manipulate the content of style sheets.
    • TRAVERSAL: This allows programs to dynamically traverse the document.
    • RANGE: This allows programs to dynamically identify a range of content in the document.
  • Level 3: consists of five different specifications: CORE3, LOAD and SAVE, VALIDATION, EVENTS, and XPATH.
    • CORE3: extends the functionality of CORE specified by DOM level 2.
    • LOAD and SAVE: This allows the program to dynamically load the content of the XML document into the DOM document and save the DOM Document into an XML document by serialization.
    • VALIDATION: This allows the program to dynamically update the content and structure of the document while ensuring the document remains valid.
    • EVENTS: extends the functionality of Events specified by DOM Level 2.
    • XPATH: XPATH is a path language that can be used to access the DOM tree.

Example: This example illustrates the dom-manipulation using getElementById() Method.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>DOM manipulation</title>
</head>

<body>
    <label>Enter Value 1: </label>
    <input type="text" id="val1" />
    <br />
    <br />
    <label>Enter Value 2: </label>
    <input type=".text" id="val2" />
    <br />
    <button onclick="getAdd()">Click To Add</button>
    <p id="result"></p>
    <script type="text/javascript">
        function getAdd() {
            
            // Fetch the value of input with id val1
            const num1 = Number(document.getElementById("val1").value);
            
            // Fetch the value of input with id val2
            const num2 = Number(document.getElementById("val2").value);
            const add = num1 + num2;
            console.log(add);
            
            // Displays the result in paragraph using dom
            document.getElementById("result").innerHTML = "Addition : " + add;
            
            // Changes the color of paragraph tag with red
            document.getElementById("result").style.color = "red";
        }
    </script>
</body>

</html>

Output:

manipulating document object using getelementbyid method

Manipulating the Document objects using getElementById() Method

Conclusion

HTML DOM is a programming interface enabling modification of web documents via functions. Focusing on HTML DOM, it empowers JavaScript to manipulate HTML tags, attributes, and elements. This guide elaborates on DOM properties, structure, methods, and benefits, fostering comprehensive understanding for web development.

Frequently Asked Questions on DOM

What do you mean by DOM?

DOM stands for Document Object Model. It is a programming interface for web documents like HTML, XML and SVG documents. DOM represents elements of documents as tree of objects.

What is an example of a DOM?

DOM representation for a HTML code can be seen as:

Document

– HTML
– head
– title (text: “My Website”)
– body
– h1 (text: “Welcome!”)
– p (text: “This is the main content.”)

What is DOM in JavaScript?

DOM in JavaScript refers to a programming interface. It provides a way to access, manipulate, and interact with the structure and content of an HTML document.

Why DOM is used in JavaScript?

DOM is used in JavaScript for many purposes like: Dynamically style and update content, performing client-side validation, event handling, etc.



Previous Article
Next Article

Similar Reads

What is the DOM (Document Object Model) ?
The DOM, or Document Object Model, is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text. The DOM provides a way for programs to manipulate the structure, style, and content of web documents dynamic
2 min read
Mongoose Document Model.prototype.model() API
The Mongoose Document API Model.prototype.model() method of the Mongoose API is used on the Document model. It allows to get the model instance. We can call this method on any model object and by providing another model name to the method parameter we will get the new instance of that model. Let us understand the model() method using an example. Sy
3 min read
How to fix “No character encoding declared at document level” in HTML Document ?
This article intends to solve the “No character encoding declared at document level” issue in your HTML program. So, before getting to the solution, we need to understand what this issue means. And for that first, we need to know about character encoding in HTML. What is character encoding in HTML? Character encoding is a system used to represent c
5 min read
HTML | DOM Object Object
The Object object represents only HTML <object> element. We can access any <object> element by using the getElementById(); and also can create object element by using createElement(); method.Syntax: It is used to access Object element document.getElementById("id"); It is used to create object element document.createElement("object"); Pr
2 min read
HTML DOM document plugins Property
The HTML DOM plugins property returns an HTMLCollectionobject containing one or more embed elements or plugins of the current document. This is a read-only property. Syntax: objects = document.plugins Return value: An HTMLCollection object, or "null" object,if there are no embedded elements or plugins in the document. Example: This example shows ho
1 min read
HTML DOM document contentType Property
The contentType property in HTML DOM returns the MIME type in which the document is being rendered. This is a read only property. Syntax: value = document.contentType; Return value: This property returns a string value of MIME content type of the document. Example: This example will show how to get the content MIME Type of the document using this p
1 min read
HTML DOM document visibilityState Property
The visibilityState property returns the visibility of the document. This is a read-only property. Syntax: letvis = document.visibilityState; Return Value: visible: When page content may be visible to the user.hidden: When page content is not visible to the user.prerender: when the document is being prerendered and is not visible to the user. Examp
1 min read
HTML DOM document scrollingElement Property
The scrollingElement property of the document returns a reference to the element that scrolls the document. In standards mode, this is the root element of the document. Whereas in quirks mode, It returns the HTML body element or NULL. Syntax: let elem = document.scrollingElement; Return Value: In standards mode, It returns the root element of the d
1 min read
HTML DOM Document hidden Property
The Document hidden property returns a Boolean value indicating if the page is considered hidden or not. This is a read-only property. Syntax: let bool = document.hidden; Return Value: This property returns a Boolean Value. true if the page is considered hidden.false if the page is not considered hidden Example: This example shows how to use this p
1 min read
HTML DOM document location Property
The Document location property returns a Location of the document, that contains information about the URL of the document. This is a read-only property. Syntax: loc = document.location; Return Value: This property returns the string URL location of the document. Example: In this example, we will learn how to get the Document Location URL using thi
1 min read
HTML DOM window document Property
The HTML DOM window document returns a reference to the document contained in the current window. Syntax: doc = window.document; Return Value: This property returns a reference to the document. Example: In this example, we will get the title of the document using that document reference. C/C++ Code <title>Window document property</title
1 min read
Mongoose Document Model.prototype.baseModelName API
The Model.prototype.baseModelName property of the Mongoose API is used to return the baseModelName as the name of the base model, if this is a discriminator model, Syntax: Model_Name.baseModelName Return Value: The Model.prototype.baseModelName property returns the baseModelName is the name of the base model, Setting up Node.js application: Step 1:
2 min read
Mongoose Document Model.updateOne() API
The Model.updateOne() method of the Mongoose API is used to update documents in a collection. This method will update the very first document that will match the filter irrespective of the value of the multi-option. Model.updateOne() method accepts four parameters: filter: It is an object to filter out a document that needs to be updated.update: It
3 min read
Mongoose Document Model.countDocuments() API
The Model.countDocuments() method of the Mongoose API is used to count the number of document present in a collection. The countDocument() method count the number of documents in a collection based on matching filter. Model.countDocuments() method accepts four parameters: filter: It is an object to filter out a document that needs to be updated.cal
3 min read
Mongoose Document Model.where() API
The Model.where() method of the Mongoose API is used to extract documents from a collection based on conditions. We can directly use where() on any model and on where() we can put various relational conditions to get the result. Model.where() returns array of objects. Each object consists of the document in a collection. Setting up Node.js applicat
3 min read
Mongoose Document Model.bulkWrite() API
The Model.bulkWrite() method of the Mongoose API is used to perform multiple operations in one command. It can insert multiple documents, can update one or multiple documents, can replace documents, can delete documents in one single command. This is faster in performance than multiple independent create commands. Syntax: Model.bulkWrite() Paramete
3 min read
Mongoose Document Model.create() API
The Model.create() method of the Mongoose API is used to create single or many documents in the collection. Mongoose by default triggers save() internally when we use the create() method on any model. Syntax: Model.create() Parameters: The Model.create() method accepts three parameters: docs: It is an object of key-value pair which will be inserted
3 min read
Mongoose Document Model.replaceOne() API
The Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters: The Model.replaceOne() method accepts four parameters: fi
3 min read
Mongoose Document Model.remove() API
The Model.remove() method of the Mongoose API is used to remove all the documents present in the collection in one go. It will be called on a Collection model which is already defined and present in the database. Syntax: Model.remove() Parameters: The Model.remove() method accepts two parameters: options: It is an object with various properties.cal
3 min read
Mongoose Document Model.prototype.deleteOne() API
The Model.prototype.deleteOne() method of the Mongoose API is used to delete any one document in a collection. This method deletes the first document that matches the condition provided to the method as a first parameter. Syntax: Model.prototype.deleteOne() Parameters: The Model.prototype.deleteOne() method accepts four parameters: condition: It is
3 min read
Mongoose Document Model.insertMany() API
The Model.insertMany() method of the Mongoose API is used to insert more than one document in the collection at a time in one go. We can provide an array of objects to the insertMany() and can be executed on the model object. Mongoose validates all the objects in the array and if any object has a validation error no object or document will get inse
4 min read
Mongoose Document Model.exists() API
The Model.exists() method of the Mongoose API is used to find documents in the database. This method returns a document with "_id" if at least one document is present in the database that matches the given filter condition. Syntax: Model.exists() Parameters: The Model.exists() method accepts four parameters: filter: It is an object which specifies
3 min read
Mongoose Document Model.inspect() API
The Model.inspect() method of the Mongoose API is used to get the model's name in the database. This method works on any model object which is defined using mongoose. Syntax: Model.inspect() Parameters: The Model.inspect() method does not accept any parameter. Return Value: The Model.inspect() function returns string. The result contains the model
2 min read
Mongoose Document Model.events API
The Model.events property of Mongoose API is used to return the model's events instance. The instance of the event contains the fields like _events, _eventsCount, and _maxListeners. Syntax: Model_Name.events Return Value: The Model.events property returns the events instance of the model. Setting up Node.js application: Step 1: Create a Node.js app
3 min read
Mongoose Document Model.prototype.discriminators API
The Model.prototype.discriminators property of the Mongoose API is used to return the registered discriminators for the model. Syntax: Model_Name.discriminators Returns: The Model.prototype.discriminators property returns the registered discriminators for the model., Setting up Node.js application: Step 1: Create a Node.js application using the fol
2 min read
Mongoose Document Model.prototype.base API
The Model.prototype.base property of the Mongoose API is used to return the base Mongoose instance the model uses. Syntax: Model_Name.base Return Value: The Model.prototype.base property returns the base Mongoose instance the model uses. Setting up Node.js application: Step 1: Create a Node.js application using the following command: npm init Step
5 min read
Mongoose Document Model.prototype.schema API
The Model.prototype.schema property of the Mongoose API is used to return the schema which the model uses. Syntax: Model_Name.schema Returns: The Model.prototype.modelName property returns the schema of the model. Setting up Node.js application: Step 1: Create a Node.js application using the following command: npm init Step 2: After creating the No
5 min read
Mongoose Document Model.prototype.modelName API
The Model.prototype.modelName property of the Mongoose API is used to return the name of the model. Syntax: Model.prototype.modelName.db Returns: The Model.prototype.modelName property returns the name of the model. Setting up Node.js application: Step 1: Create a Node.js application using the following command: npm init Step 2: After creating the
2 min read
Mongoose Document Model.deleteOne() API
The Model.deleteOne() method of the Mongoose API is used to delete a document from the collection. We can provide an object of the field to the deleteOne() and can be executed on the model object. It will delete the first document that matches the condition from the collection. Syntax: Model.deleteOne() Parameters: The Model.deleteOne() method acce
3 min read
Mongoose Document Model.deleteMany() API
The Model.deleteMany() method of the Mongoose API is used to delete more than one document in the collection at a time in one go. We can provide an object which contains a condition to the deleteMany() and can be executed on the model object. It will delete all the documents from the collection that will match the given condition. Syntax: Model.del
3 min read
Article Tags :