After learning the basics of JavaScript, I started learning about the DOM.
At first, DOM sounded complicated. But when I understood how JavaScript can interact with HTML elements, it became much easier.
What is DOM?
DOM stands for Document Object Model.
The browser converts an HTML page into a structure that JavaScript can understand and modify.
For example:
<h1>Hello World</h1>
JavaScript can find this
and change its content.
Selecting an Element
We can use getElementById() to select an HTML element.
<h1 id="title">Hello World</h1>
let heading = document.getElementById("title");
console.log(heading);
Changing Text
We can change the text using textContent.
heading.textContent = "Hello JavaScript!";
Now the webpage displays:
Hello JavaScript!
Changing CSS
JavaScript can also change the style of an element.
heading.style.color = "blue";
heading.style.fontSize = "40px";
Handling Button Clicks
We can use an event listener to respond when a user clicks a button.
<button id="btn">Click Me</button>
let button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Button clicked!");
});
Now something happens when the button is clicked. 🎯
Creating Elements
JavaScript can even create new HTML elements.
let paragraph = document.createElement("p");
paragraph.textContent = "I created this using JavaScript!";
document.body.appendChild(paragraph);
Why is DOM Important?
DOM helps us create interactive websites.
With DOM, we can:
Change HTML content
Change CSS styles
Add or remove elements
Handle button clicks
Validate forms
Create dynamic web pages
Easy Way to Remember 🧠
Think of it like this:
HTML → Creates the structure 🏗️
CSS → Makes it beautiful 🎨
JavaScript + DOM → Makes it interactive ⚡
Conclusion
Learning the DOM helped me understand how JavaScript actually interacts with a webpage.
My next step is to practice more DOM concepts by building small projects.
Learn → Practice → Build → Improve 🚀
Top comments (0)