DOM stands for Document Object Model. It is a programming interface for HTML and XML documents. It represents the page so that programs can change the structure, style, and content of a document dynamically.
The browser parses HTML and builds a tree-like structure known as the DOM tree. JavaScript can then use this structure to access and modify elements using the document object.
document is an Object?
In JavaScript, everything is an object. The document is a global object provided by the browser that represents the entire HTML page. It has properties and methods to interact with and manipulate the page.
We use various methods on document to access HTML elements:
getElementById()Targets a single element by its ID.
const title = document.getElementById("main-title");
getElementsByClassName()Returns a collection of all elements with the given class name.
const items = document.getElementsByClassName("item");
getElementsByTagName()Returns a collection of elements with the specified tag (like <p>, <div>).
const paragraphs = document.getElementsByTagName("p");
querySelector()Returns the first element that matches a CSS selector.
const firstItem = document.querySelector(".item");
querySelectorAll()Returns all elements that match a CSS selector.
const allItems = document.querySelectorAll(".item");
// HTML: <h1 id="header">Hello</h1>
const header = document.getElementById("header");
header.textContent = "Welcome to DOM";
// HTML: <button id="clickBtn">Click Me</button>
document.getElementById("clickBtn").addEventListener("click", function() {
alert("Button Clicked!");
});