Skip to content

What is DOM in JavaScript?

DOM stands for Document Object Model. It is a application programming interface (API) for HTML and XML documents. The browser converts the webpage to a document object so that it is understood by JavaScript. That document object is DOM. Thus, DOM characterizes the HTML and XML documents as objects.

Why DOM?

JavaScript does not understand HTML documents. It cannot understand what is a <p> or a <h2> tag. Instead, it understands objects.

Thus, when an HTML file is loaded into the browser, it is converted into a document object. The document object is easily interpreted by JavaScript. Once interpreted, Javascript can easily access the elements, class, id of the HTML page.

Using DOM, JavaScript can provide dynamicity to the web page. It can:

  • Add, change or remove the HTML elements in the web page.
  • Add, alter or remove the HTML attributes in the web page.
  • Change the CSS styles of the web page.
  • Add HTML events in the web page.

Also read: How do browsers work? The science behind rendering a webpage


The DOM Tree

The DOM created by the browser while loading the web page is represented as a tree of elements.

The DOM Tree.

The document is the root element of the DOM tree which represents the HTML document. With the help of document, you can access all the elements of the HTML webpage and add dynamicity to your web page. Below the document object, you can see the other HTML objects in the tree.

Also read: How to fix error in plot new: Figure margins too large?


Methods of DOM

There are many methods of document object. Let’s look into some of the essential methods.

getElementById()

The getElementById() method fetches the element by their ID, and then you can add text to the element or play with its CSS style. See the example given below.

The output of the above code:


getElementsByName()

The getElementByName() method collects a list of all the elements in the
document having a specific name. You can access the elements in the list using an index. See the example given:

The output of the above code:

Also read: How to fix error in file rt: Cannot open the connection?


getElementsByTagName()

The getElementsByTagName() method fetches all the elements using a particular tag. You can access the elements in the list using an index

The output of the above code:


getElementsByClassName()

The getElementsByClassName() method fetches all the elements having a
particular class as objects. You can use those objects using the index. See the
example given:

The output of the above code:

Also read: How to enable or disable Javascript in Firefox?

Hello There!

If you like what you read, please support our publication by sharing it with your friends, family and colleagues. We're an ad-supported publication. So, if you're running an Adblocker, we humbly request you to whitelist us.







>