What is DOM in JavaScript?
“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”
What is the HTML DOM?
The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a web page as a tree of objects, where each object corresponds to part of the page (such as elements, attributes, text, and more). JavaScript can be used to interact with and manipulate the DOM, enabling dynamic changes to a webpage after it has been loaded.
In simpler terms, the DOM allows JavaScript to access, modify, add, or delete elements and content on a web page.
Example:
document.getElementById(id).innerHTML = new HTML
How the DOM Works?
-
Document: Refers to the entire HTML or XML document.
-
Object: Represents an element in the document. Elements like
<div>
,<p>
, and<img>
are objects within the DOM.
The DOM turns the HTML structure of a webpage into a tree structure, with each node (or object) representing part of the page.
For example:
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1>Welcome to My Page</h1>
<p>This is a paragraph.</p>
</body>
</html>
How JavaScript Interacts with the DOM
-
Access elements: Find HTML elements by their ID, class, tag name, etc.
-
Modify elements: Change content, style, attributes, etc.
-
Create new elements: Dynamically add new content to the page.
-
Remove elements: Delete content from the page.