A Platform To Learn To Code

JAVASCRIPT DOM INTRODUCTION



What is DOM?

The DOM stands for Document Object Model. DOM is an interface that allows developers to interact and control the Elements of the web.

The Document Object Model is an interface for HTML and XML documents. Using DOM each and every element of the document is accessible.

The W3C standard comprises three sections: DOM core, XML DOM and HTML DOM. We will learn here about HTML DOM.

At a basic level webpage is made up of a tree of elements, these elements are objects. The structure of document made up of these objects is called Document Object Model.

Refer below image to understand how HTML documents are structured.

HTML DOM Tree
document-object-model

You can see from the above image how elements are structured in a document. The document holds everything about a webpage. We will learn more about it in the next chapter.


  • Document Object Model is not a set of data structure. It is an object model that specifies interface.
  • DOM is not some special stuff; the html code that you write that code when structured in the form of a tree is DOM.

DOM Tree Structure

The DOM comprises different types of nodes. Each type of node has a different way to be accessed.

  • Element Nodes - Element nodes are themselves called objects in DOM. It comprises most of the DOM which holds other data like text and attributes. Example p, h1, h2, ul, li etc
  • Attribute Nodes - Attribute nodes are attached to the element node and adds extra information to the element. Example title attribute, class attribute etc.
  • Text Node - Text nodes are contents of the elements and have no children like element nodes.

The DOM has hierarchical structure. The lower elements are children of upper connected elements and side elements having the same parents are called siblings.


Accessing DOM Elements

The HTML elements are accessed by using javascript.

There are many DOM methods using which you can access HTML elements, example - getElementById("id1"). We will discuss more of these methods later in the chapters.

Example

Run the code

Let's first understand what we can do with these elements using javascript.

  • Javascript can change and add content of the element
  • Javascript can add or change style (CSS) of the element
  • Javascript can set new attributes to the element and can remove and modify older attributes
  • Javascript can add new element in the DOM structure
  • Javascript can create and add events to the element
  • Javascript can delete elements from the DOM tree

Visualising HTML Code in DOM Tree

Example

DOM Tree of above example

html dom tree example
Javascript DOM Document