DOM Manipulation—Basics

Learn what the Document Object Model (DOM) is, as well as how JavaScript interacts with HTML code.

What is DOM?

DOM stands for Document Object Model. In simple terms, the DOM is a tree generated by the browsers to make the complete HTML code visible to the user. The DOM is a standard and language-independent interface that allows any scripting language, such as JavaScript, to modify the contents of a web page dynamically and efficiently by using the DOM tree. Each element or tag in HTML is converted to a node and is attached to its parent node (under which a tag is defined). Each DOM tree has a root node called "Document." Under this node, all the HTML nodes reside.

Understand DOM from HTML code

Let's look at the HTML code shown below, then look at the DOM tree of the HTML code.

Press + to interact
<html>
<head>
<title>Welcome to the Course!</title>
</head>
<body>
<div>
<p>We are learning JavaScript</p>
</div>
</body>
</html>

The HTML code given above is a basic HTML code that displays a paragraph in the browser with the web page's title. Now let's see the DOM tree generated below:

%0 node_1 DOCUMENT node_3 HTML node_1->node_3 node_1655380740387 HEAD node_3->node_1655380740387 node_1655382079871 #text node_3->node_1655382079871 node_1655382078792 BODY node_3->node_1655382078792 node_1655382109900 #text node_1655380740387->node_1655382109900 node_1655382120027 TITLE node_1655380740387->node_1655382120027 node_1655382119278 #text node_1655380740387->node_1655382119278 node_1655382128399 #text node_1655382078792->node_1655382128399 node_1655382135756 DIV node_1655382078792->node_1655382135756 node_1655382135259 #text node_1655382078792->node_1655382135259 node_1655382150390 node_1655382109900->node_1655382150390 node_1655382182984 #text node_1655382120027->node_1655382182984 node_1655382167284 node_1655382119278->node_1655382167284 node_1655382173605 node_1655382128399->node_1655382173605 node_1655382350777 #text node_1655382135756->node_1655382350777 node_1655382360272 p node_1655382135756->node_1655382360272 node_1655382359903 #text node_1655382135756->node_1655382359903 node_1655382177736 node_1655382135259->node_1655382177736 node_1655382314375 Welcome to the Course! node_1655382182984->node_1655382314375 node_1655382368534 #text node_1655382360272->node_1655382368534 node_1655382375181 We are learning JavaScript node_1655382368534->node_1655382375181
DOM Tree for the sample HTML code discussed above

Explanation:

  • Every DOM tree's root will be an object named Document.

  • Using the tree's root, JavaScript can access any part of the web page by traversing the tree.

  • Every element (tag) and the text (even if there is a space or a newline character in the HTML code) is converted to a node in the tree. ...

Access this course and 1400+ top-rated courses and projects.