Understanding how JavaScript interacts with HTML
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
Each part of the HTML document becomes a node in the DOM tree.
JavaScript can find elements in the DOM using different methods.
document.getElementById("myId");
document.querySelector(".className");
document.querySelectorAll("p");
Once you select an element, you can change its content.
const el = document.getElementById("demo");
el.textContent = "New text";
You can also modify CSS styles directly from JavaScript.
const el = document.getElementById("demo");
el.style.color = "blue";
el.style.fontSize = "20px";
JavaScript can create new elements dynamically.
const p = document.createElement("p");
p.textContent = "Hello DOM";
document.body.appendChild(p);
The DOM allows JavaScript to respond to user actions like clicks or typing.
const button = document.getElementById("btn");
button.onclick = function() {
alert("Button clicked!");
};
<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.