Understanding The Document Object Model(DOM)

Anujkumar Yadav
4 min readSep 22, 2021

So What is DOM?

When you open a web page in your browser, Then browser creates a representation of that document known as a document object model and this document enables JavaScript to access and manipulate the elements of websites and also add functionality to our page.

DOM is not part of the JavaScript language but is instead a Web API used to build websites

The HTML DOM model is constructed as a tree of Objects

Example,

In Html:-

In DOM, the above code is represented as a DOM tree:

DOM Document

The DOM Document is the owner of all other objects in your webpage. That means if you want to access any object on your webpage you always have to start with the document. It also contains many important properties and methods that enable us to access and modify our website. For instance,

Accessing the elements

To apply styles or functionality to an element using JS, we need to first select that element and then do what we have to do to that element. For accessing, DOM provides many inbuilt functions that we can use to select that element.

document.getElementById()

The getElementById() method returns the element that has the ID attribute with the specified value. For eg,

document.getElementsByClassName()

The getElementsByClassName() method returns an array-like object of all child elements which have all of the given class name. For eg,

document.getElementsByTagName()

The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as an HTML collection object.

document.querySelector()

document.querySelector() returns the first element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned. We don’t have to use different methods for different tags.

document.querySelectorAll() returns a Node List representing a list of the document’s elements that match the specified group of selectors. If no matches are found, null is returned.

Examples of querySelector() and querySelectorAll():

Manipulating the elements

The HTML DOM allows us to change the content and style of an HTML element by changing its properties.

innerHTML

The JavaScript innerHTML property sets the HTML contents of an element on a web page. InnerHTML is a property of the HTML DOM

InnerHTML can also be used to put tags in another tag:

innerText

The JavaScript innerText property sets the text content of an element

Changing the style

To change the style of an HTML element we need to change the style property of our elements. Here is the syntax for changing the color of paragraph style on an element:

We need to write the in camelcase instead of the normal CSS property name. In this example, we used borderBottom instead of border-bottom.

For more info, questions or compliments, leave a comment on the comment section below!😁😁

--

--