SmartCodingTips

HTML DOM (Document Object Model)

The HTML DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content dynamically.

What is the DOM?

The DOM is a tree-like structure where each element, attribute, and piece of text in the HTML document is represented as an object. JavaScript can use this model to access and modify web pages on the fly.

DOM Hierarchy

Here's a simplified example of how HTML is represented in the DOM:


<html>
  <body>
    <h1>Hello World</h1>
    <p>This is a paragraph.</p>
  </body>
</html>
            

In the DOM, <html> is the root node, <body> is a child of <html>, and so on.

Accessing DOM Elements with JavaScript

You can use JavaScript to access and modify elements like this:


// Get an element by ID
const heading = document.getElementById("mainHeading");
heading.textContent = "Updated Heading";
            

Common DOM Methods

  • getElementById()
  • getElementsByClassName()
  • getElementsByTagName()
  • querySelector() and querySelectorAll()
  • createElement(), appendChild()
  • innerHTML, textContent, setAttribute()