š JavaScript DOM (Document Object Model) ā Explained Simply
The DOM (Document Object Model) is a programmatic interface that allows JavaScript to interact with and manipulate HTML and CSS of a webpage dynamically.
š§ The DOM turns your HTML page into a tree of nodes (elements, text, attributes) that JS can control.
š§± What Is the DOM?
Imagine this HTML:
html
<body>
<h1 id="title">Hello</h1>
<button>Click Me</button>
</body>
Behind the scenes, the browser creates this structure:
php-template
Document
āāā <html>
āāā <body>
āāā <h1 id="title">
āāā <button>
ā Each tag becomes a node (an object you can access via JavaScript).
š Accessing the DOM
1. Selectors
js
document.getElementById("title");
document.querySelector("h1");
document.querySelectorAll("button");
2. Traversing Nodes
js
const el = document.getElementById("title");
el.parentNode;
el.nextElementSibling;
el.firstChild;
š§āšØ Manipulating Elements
š Change Content
js
el.textContent = "New Text";
el.innerHTML = "<span>Styled</span>";
šØ Change Style
js
el.style.color = "red";
el.classList.add("highlight");
š§± Change Attributes
js
el.setAttribute("id", "new-id");
el.getAttribute("id");
el.removeAttribute("id");
š§© Creating/Removing Elements
js
const newEl = document.createElement("p");
newEl.textContent = "New Paragraph";
document.body.appendChild(newEl); // add to page
document.body.removeChild(newEl); // remove from page
š±ļø Event Handling
js
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
alert("Button clicked!");
});
šÆ You can also use:
mouseover
keydown
submit
change
š§Ŗ Example: Toggle Dark Mode
html
<button id="toggle">Toggle Dark Mode</button>
<script>
document.getElementById("toggle").addEventListener("click", () => {
document.body.classList.toggle("dark");
});
</script>
š§° Common DOM Methods & Properties
Method/Property | Description |
---|---|
document.querySelector() | Select first matching element |
element.innerHTML | Get/set HTML inside element |
element.textContent | Get/set plain text |
element.classList | Add/remove CSS classes |
element.style | Inline styles |
document.createElement() | Create a new DOM element |
parent.appendChild() | Add element to DOM |
element.addEventListener() | Attach event listener |
Ā
š Learn More
š MDN DOM Guide
ā Summary
What | DOM Lets You Do |
---|---|
Access elements | ā |
Change content or styles | ā |
Respond to user actions | ā |
Build dynamic UIs | ā |