The Document Object Model (DOM) is a programming interface for web documents.
It represents the
structure of a document as a tree of nodes, where each node corresponds to a part of the document,
such as an element, attribute, or text. The DOM allows programming languages, such as JavaScript, to
interact with and manipulate web pages dynamically.
Key Concepts of the DOM
1. Nodes and Elements:
o The DOM represents the document as a tree of nodes. The most common types of
nodes are elements, attributes, and text.
o Elements are the building blocks of an HTML document (e.g., <div>, <p>, <a>).
2. Tree Structure:
o The DOM is structured as a tree. The document itself is the root, with various child
nodes branching out from it.
o For example, an HTML document has a root node (<html>), which has children nodes
like <head> and <body>.
3. Interacting with the DOM:
o You can use JavaScript to access and manipulate the DOM. This includes creating,
modifying, and deleting elements, attributes, and text within a document.
Example of DOM Manipulation
Here is a simple example demonstrating how to interact with the DOM using JavaScript:
HTML
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<p>This is a paragraph.</p>
<button id="changeTitle">Change Title</button>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js)
javascript
Copy code
// Accessing an element by its ID
let titleElement = document.getElementById('title');
// Changing the text content of the element
titleElement.textContent = 'Hello, DOM!';
// Adding an event listener to the button
document.getElementById('changeTitle').addEventListener('click', function() {
titleElement.textContent = 'Title Changed!';
});
DOM Methods and Properties
Here are some commonly used DOM methods and properties:
Selecting Elements:
o document.getElementById('id')
o document.getElementsByClassName('class')
o document.getElementsByTagName('tag')
o document.querySelector('selector')
o document.querySelectorAll('selector')
Modifying Elements:
o element.textContent or element.innerHTML
o element.setAttribute('attribute', 'value')
o element.style.property = 'value'
o element.classList.add('class')
o element.classList.remove('class')
Creating and Appending Elements:
o document.createElement('tag')
o parentElement.appendChild(newElement)