Introduction to DOM in Javascript

Introduction to DOM in Javascript

It is a visual representation of the objects that build the structure and content of the document over the web. Understanding the DOM is fundamental for anyone looking to enhance their web development skills.

What is DOM?

DOM serves as the programming interface for web-based documents, It represents the page so that programs can manipulate the document structure, content, and style.

Example HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM Learning</title>
</head>
<body>
    <div class="bg_black">
        <h1 class="heading">DOM learning on Chai Aur Code</h1>
        <p>Lorem ipsum dolor sit amet.</p>
    </div>
</body>
</html>

In this HTML document, we have a few elements:

  • A <!DOCTYPE html> declaration which defines the document type and version of HTML.

  • The <html> element, which is the root element of an HTML page.

  • The <head> element containing metadata about the document, including its character set and title.

  • The <body> element, which contains the content of the document, including a div with a class of bg_black, an h1 heading, and a p paragraph.

When this HTML is loaded in a browser, the DOM represents it as a tree of objects. Each element in the HTML becomes a node in the DOM, which can be accessed and manipulated using JavaScript.

Console Logging the Window Object

If you log the window object in the browser console with console.log(window), you will see the global object which is window. Inside that window object, we have the document object, which represents the loaded HTML document. The document object contains properties for accessing and manipulating the content of the HTML document, including the html, head, and body elements.

Here's how the DOM hierarchy looks for the provided HTML example:

The graphical representation above shows how the DOM hierarchy is structured, starting from the window object at the top, which contains the document object, and further breaking down into html, head, body, and other nested elements.