What is the DOM? Javascript tutorial
Diagram showing Hypertext Markup Language elements represented as a DOM tree with nodes - javascript tutorial
What is the DOM?
DOM stands for Document Object Model. It is a programming interface provided by the browser that allows JavaScript (or any programming language) to interact with and manipulate the content, structure, and style of a webpage dynamically.
The DOM represents the entire HTML document as a tree structure.
Each HTML element is represented as a node.
The document itself is the root node.
JavaScript can use the DOM to:
Read or modify content (e.g., text, attributes)
Add or remove elements
Change CSS styles
Handle user events like clicks or keypresses
1. Selecting DOM Elements
document.getElementById("myId");
document.getElementsByClassName("myClass");
document.getElementsByTagName("p");
document.querySelector("#myId");
document.querySelectorAll(".myClass");
2. Changing Content
document.getElementById("demo").innerHTML = "Hello World!";
3. Changing Attributes
document.getElementById("myImage").src = "new-image.jpg";
4. Changing Styles
document.getElementById("box").style.backgroundColor = "blue";
5. Creating and Appending Elements
let newDiv = document.createElement("div");
newDiv.innerHTML = "New Div Element";
document.body.appendChild(newDiv);
6. Removing Elements
let element = document.getElementById("oldDiv");
element.remove();
7. Event Handling
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
Real-Life Example:
<button id="changeText">Click Me</button>
<p id="text">Old Text</p>
<script>
document.getElementById("changeText").addEventListener("click", function() {
document.getElementById("text").innerHTML = "New Text!";
});
</script>
Why Learn DOM Manipulation?
Interactive Websites: Add behavior like dropdowns, sliders, and modals.
Dynamic Content: Update parts of the page without reloading (AJAX + DOM).
Modern Web Development: DOM is the foundation of libraries/frameworks like React, Vue, and Angular.
Conclusion:
Mastering DOM manipulation is essential for any front-end developer. It empowers you to create dynamic and interactive websites that respond to user actions and data changes in real-time.
Want to explore DOM further? Try building a simple to-do list or form validation feature using just JavaScript and the DOM!