What is DOM in JavaScript?
DOM stands for Document Object Model. It is a programming interface provided by the browser that represents an HTML document as a tree of objects. JavaScript uses the DOM to access and modify the elements of a web page.
For example, if we have an HTML element like:
<h1 id="title">Hello</h1>
JavaScript can access this element through the DOM:
const title = document.getElementById("title");
Here, getElementById() returns an object that represents the <h1> element. It is not simply returning the text "Hello". The returned object contains properties and methods related to that HTML element.
Because it returns an object, we can access its properties using the dot (.) operator:
console.log(title.textContent);
console.log(title.id);
console.log(title.tagName);
We can also modify the element:
title.textContent = "Hello World";
title.style.color = "red";
We can even call methods on the returned object:
title.remove();
We can also directly access a property from the returned object without storing it in a variable:
document.getElementById("title").textContent = "Hello World";
Here, getElementById("title") first returns the <h1> element object, and then .textContent accesses a property of that returned object.
The DOM also provides many other methods for finding and modifying elements, such as querySelector(), createElement(), appendChild(), and addEventListener().
In simple terms, HTML defines the structure of the page, the DOM represents that structure as objects, and JavaScript uses those objects to interact with and modify the page. The DOM itself is not part of the JavaScript language; it is a browser-provided API that JavaScript can use.
Top comments (0)