DEV Community

Aman Kumar
Aman Kumar

Posted on

🧠 DOM Unlocked: Learn the Document Object Model Like a Pro!

📄 What is the DOM?

DOM stands for Document Object Model.

It’s a programming interface that represents your HTML document as a tree of objects that JavaScript can interact with.

Example Breakdown:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>DOM Learning</title>
  </head>
  <body>
    <div class="bg-black">
      <h1 id="title" class="heading">DOM Learning on Chai Aur Code</h1>
      <p>Lorem ipsum dolor sit amet.</p> 
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here, the browser transforms this HTML into a DOM tree, where each tag becomes a node that JavaScript can access and change.


🔍 Exploring the DOM in the Browser Console

You can try these directly in your browser’s console:

console.log(window); // The global window object
console.log(window.document); // Gives you the HTML document
console.log(document); // Shortcut for above
console.dir(document); // Reveals properties and methods in object-like view
Enter fullscreen mode Exit fullscreen mode

Want to grab the third link on a page?

console.log(document.links[2]); // Not an array, but an HTMLCollection
Enter fullscreen mode Exit fullscreen mode

✋ DOM Manipulation 101

Let's try selecting and updating DOM elements using JavaScript.

🧾 Example:

Select an element by ID:

document.getElementById('title');
Enter fullscreen mode Exit fullscreen mode

Change the content inside that element:

document.getElementById('title').innerHTML = "<h1>Chai Aur Code</h1>";
Enter fullscreen mode Exit fullscreen mode

This line replaces the original heading content with your own.


🌐 Practice It Yourself

Try these out on a real webpage like:

👉 Wikipedia – Brendan Eich

document.getElementById('firstHeading');
document.getElementById('firstHeading').innerHTML = "Chai Aur Code";
Enter fullscreen mode Exit fullscreen mode

Boom! You’ve just changed a live website’s heading (on your browser only 😄).


📌 Quick Notes

DOM Feature Description
window Global object containing browser environment
document Represents the web page
getElementById() Selects an element with a specific ID
innerHTML Gets or sets the HTML content inside an element
console.dir(document) Displays the DOM tree as a JS object

🧠 Final Thoughts

DOM is the bridge between your HTML and JavaScript. It allows you to:

  • Read content from the page
  • Update styles, text, and attributes
  • Respond to user actions

Top comments (0)