DOM
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects, allowing programs to manipulate the document's structure, style, and content. The DOM is language-agnostic, meaning it can be used with any programming language, but it is most commonly associated with JavaScript in web development.
Key Parts of the DOM
Document: The root of the DOM tree. It represents the entire HTML or XML document.
Element: Represents an HTML or XML element. Elements can have attributes and can contain other elements or text nodes.
Attribute: Represents an attribute of an element. Attributes provide additional information about elements.
Text: Represents the text content of an element or attribute.
Node: The base class for all DOM objects. Elements, attributes, and text are all types of nodes.
Comment: Represents a comment in the document.
DocumentFragment: Represents a minimal document object that can hold a portion of the document structure.
How the DOM is Used
Accessing Elements: You can access elements using methods like
getElementById,getElementsByClassName,getElementsByTagName,querySelector, andquerySelectorAll.Manipulating Elements: You can create, remove, and modify elements and their attributes using methods like
createElement,appendChild,removeChild,setAttribute, andremoveAttribute.Event Handling: You can attach event listeners to elements to handle user interactions using methods like
addEventListenerandremoveEventListener.
Example
Here is a simple example demonstrating some basic DOM manipulations:
In this example:
The
document.getElementByIdmethod is used to access thedivelement with the idcontent.An event listener is added to the button to change the text content of the
divwhen the button is clicked.