DOM (Document Object Model)
When a browser loads a web page, it converts the HTML into a structured tree of objects. This tree is called the DOM. Each element becomes a node (object) that JavaScript can interact with.
Example HTML:
<body>
<h1>Hello</h1>
<p>Welcome</p>
</body>
DOM structure:
Document
└── html
└── body
├── h1
└── p
Why is DOM important?
- Access elements
- Modify content
- Change styles
- Handle events (clicks, typing, etc.)
Accessing Elements in the DOM:
JavaScript provides several ways to select and access elements in a web page. Here are the most commonly used methods:
Selects a single element with a specific id
const element = document.getElementById("title");
Returns a collection of elements with the given class
const elements = document.getElementsByClassName("item");
Selects all elements with a specific tag (like <p>)
const elements = document.getElementsByTagName("p");
Selects the first matching element using CSS selectors
const element = document.querySelector(".item");
Selects all matching elements (returns a NodeList)
const elements = document.querySelectorAll(".item");
Modifying Content in the DOM
JavaScript provides different ways to modify content, and each behaves slightly differently.
<div id="demo">
Hello <span style="display:none;">Hidden</span> World
</div>
textContent:
textContent includes all text inside an element, even content that is hidden using CSS. It ignores any HTML tags and treats everything as plain text, making it a safer and cleaner option.
document.getElementById("demo").textContent;
Output:
Hello Hidden World
innerText
innerText shows only the text that you can see on the page. If something is hidden using CSS (like display: none), it will not be shown.
document.getElementById("demo").innerText;
Output:
Hello World
innerHTML
document.getElementById("demo").innerHTML;
Output:
Hello <span style="display:none;">Hidden</span> World
Changing Styles in the DOM
JavaScript can change how elements look on a web page. You can change colors, size, background, or even hide elements using styles.
Example:
element.style.backgroundColor = "yellow";
element.style.color = "red";
element.style.fontSize = "20px";
element.style.display = "none";
Handling Events in the DOM
Events are actions performed by the user, like clicking a button or typing in a box. JavaScript listens for these events and runs code when they happen, making the website interactive.
Example:
<button id="btn" onclick="clickHandler()">Click Me</button>
<script>
function clickHandler() {
alert("Button clicked!");
}
</script>
Top comments (0)