JavaScript DOM Basics
Hello World
Welcome to my website
JavaScript access: let title = document.getElementById("title"); console.log(title.textContent); // Output: Hello World Common Ways to Access DOM Elements By ID let header = document.getElementById("header"); By Class Name let items = document.getElementsByClassName("menu-item"); By Tag Name let paragraphs = document.getElementsByTagName("p"); Using querySelector / querySelectorAll let firstItem = document.querySelector(".menu-item"); let allItems = document.querySelectorAll(".menu-item"); Manipulating DOM Elements Change Text Content title.textContent = "Welcome to My Site"; Change Styles title.style.color = "blue"; title.style.fontSize = "24px"; Add / Remove Classes title.classList.add("highlight"); title.classList.remove("highlight"); Create New Elements let newPara = document.createElement("p"); newPara.textContent = "This is a new paragraph"; document.body.appendChild(newPara); Event Handling You can make pages interactive by responding to user actions: let button = document.getElementById("myBtn"); button.addEventListener("click", function() { alert("Button clicked!"); }); Mini Challenge Try to: Add a new list item to an existing- using JavaScript.
Change the background color of a
when clicked.
Best Practices
Use querySelector/querySelectorAll for more flexibility
Avoid inline JavaScript in HTML
Keep DOM manipulation efficient (cache selectors)
Test in different browsers for compatibility
Conclusion
Understanding the DOM is key to creating interactive web pages. With this guide:
You can access, modify, and style elements dynamically
You can handle events to create user interactions
You’re ready to build more advanced JavaScript projects
Learn JavaScript DOM basics with step-by-step examples, element selection, event handling, and practical tips for beginners.
Add Comment
comment url