JavaScript DOM (Document Object Model) - Complete Guide

JavaScript DOM (Document Object Model) - Complete Guide

The DOM (Document Object Model) represents the structure of a web page and allows JavaScript to manipulate HTML and CSS dynamically.

What is the DOM?

  • The DOM is a tree-like structure where each HTML element is represented as an object.

  • It allows JavaScript to interact with and modify the web page.

  • The document object is the entry point to the DOM.


1. Accessing Elements in the DOM

1. getElementById() (Select a single element by id)

<h1 id="main-title">Hello World</h1>
<script>
let title = document.getElementById("main-title");
console.log(title.textContent); // Output: Hello World
</script>

Output: Hello World


2. getElementsByClassName() (Select multiple elements by class)

<p class="description">This is a paragraph.</p>
<p class="description">Another paragraph.</p>

<script>
let paragraphs = document.getElementsByClassName("description");
console.log(paragraphs[0].textContent); // Output: This is a paragraph.
console.log(paragraphs.length); // Output: 2
</script>

Output:

This is a paragraph.
2

3. getElementsByTagName() (Select elements by tag)

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<script>
let allParagraphs = document.getElementsByTagName("p");
console.log(allParagraphs[0].textContent); // Output: This is a paragraph.
</script>

Output: This is a paragraph.


4. querySelector() (Selects the first matching element)

<p class="description">This is a paragraph.</p>
<p class="description">Another paragraph.</p>

<script>
let firstParagraph = document.querySelector(".description");
console.log(firstParagraph.textContent); // Output: This is a paragraph.
</script>

Output: This is a paragraph.


5. querySelectorAll() (Selects all matching elements)

<button>Button 1</button>
<button>Button 2</button>

<script>
let allButtons = document.querySelectorAll("button");
console.log(allButtons.length); // Output: 2
</script>

Output: 2


2. Modifying DOM Elements

1. Changing Text Content

<h1 id="main-title">Old Title</h1>

<script>
document.getElementById("main-title").textContent = "New Title";
console.log(document.getElementById("main-title").textContent); 
// Output: New Title
</script>

Output: New Title


2. Changing Inner HTML

<h1 id="main-title">Old Title</h1>

<script>
document.getElementById("main-title").innerHTML = "<span style='color: red;'>New Title</span>";
</script>

Output: New Title (in red color)


3. Changing CSS Styles

<h1 id="main-title">Styled Title</h1>

<script>
document.getElementById("main-title").style.color = "blue";
document.getElementById("main-title").style.fontSize = "30px";
</script>

Output: The text "Styled Title" appears in blue color and larger size.


4. Adding and Removing Classes

<h1 id="main-title">Hello</h1>

<style>
.highlight { color: red; font-size: 25px; }
</style>

<script>
let title = document.getElementById("main-title");
title.classList.add("highlight"); // Adds the class
console.log(title.classList.contains("highlight")); // Output: true
title.classList.remove("highlight"); // Removes the class
console.log(title.classList.contains("highlight")); // Output: false
</script>

Output:

true
false

3. Creating and Removing Elements

1. Creating a New Element

<script>
let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div";
document.body.appendChild(newDiv); // Adds it to the body
</script>

Output: A new <div> appears with the text "This is a new div".


2. Removing an Element

<h1 id="main-title">I will be removed</h1>

<script>
document.getElementById("main-title").remove();
</script>

Output: The <h1> element disappears.


3. Replacing an Element

<h1 id="main-title">Old Heading</h1>

<script>
let newHeading = document.createElement("h2");
newHeading.textContent = "New Heading";
let oldHeading = document.getElementById("main-title");
document.body.replaceChild(newHeading, oldHeading);
</script>

Output: "Old Heading" is replaced with "New Heading" (in <h2> tag).


4. Event Listeners in the DOM

1. Using addEventListener()

<button id="myButton">Click Me</button>

<script>
document.getElementById("myButton").addEventListener("click", function() {
    alert("Button Clicked!");
});
</script>

Output: Clicking the button shows an alert saying "Button Clicked!".


5. Form Handling

<form id="myForm">
    <input type="text" id="username" placeholder="Enter name">
    <button type="submit">Submit</button>
</form>
<p id="output"></p>

<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevents page reload
    let name = document.getElementById("username").value;
    document.getElementById("output").textContent = "Hello, " + name;
});
</script>

Output: Entering "John" and clicking Submit displays "Hello, John".


6. setTimeout and setInterval

1. setTimeout

setTimeout(function() {
    console.log("This appears after 3 seconds");
}, 3000);

Output: "This appears after 3 seconds" (after 3 sec).


2. setInterval

setInterval(function() {
    console.log("Repeating every 2 seconds");
}, 2000);

Output: Prints "Repeating every 2 seconds" repeatedly.


7. Local Storage

localStorage.setItem("username", "JohnDoe");
console.log(localStorage.getItem("username")); // Output: JohnDoe
localStorage.removeItem("username");
console.log(localStorage.getItem("username")); // Output: null

Output:

JohnDoe
null

Conclusion

  • The DOM enables JavaScript to manipulate HTML and CSS dynamically.

  • We can access, modify, add, remove, and traverse elements.

  • Event listeners allow interaction.

  • Form handling & storage enhance functionality.