The DOM (Document Object Model)

Understanding how JavaScript interacts with HTML

What is the DOM?

The DOM (Document Object Model) is a structured representation of an HTML document. The browser converts HTML into a tree of objects that JavaScript can read and modify.

document
 └── html
      └── body
           ├── h1
           └── p
  

The DOM as a Tree

Each part of the HTML document becomes a node in the DOM tree.

Accessing Elements

JavaScript can find elements in the DOM using different methods.

document.getElementById("myId");
document.querySelector(".className");
document.querySelectorAll("p");
  

Modifying Content

Once you select an element, you can change its content.

const el = document.getElementById("demo");
el.textContent = "New text";
  

Changing Styles

You can also modify CSS styles directly from JavaScript.

const el = document.getElementById("demo");
el.style.color = "blue";
el.style.fontSize = "20px";
  

Creating Elements

JavaScript can create new elements dynamically.

const p = document.createElement("p");
p.textContent = "Hello DOM";
document.body.appendChild(p);
  

Events

The DOM allows JavaScript to respond to user actions like clicks or typing.

const button = document.getElementById("btn");
button.onclick = function() {
  alert("Button clicked!");
};
  

Why the DOM is Important

Example: Simple Interaction

<input id="name">
<button onclick="show()">Show</button>
<p id="output"></p>

function show() {
  const value = document.getElementById("name").value;
  document.getElementById("output").textContent = value;
}
  

This example shows how the DOM connects user input to visible output.