The Document Object Model
The Document Object Model
The Document Object Model
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.
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>.
o You can use JavaScript to access and manipulate the DOM. This includes creating,
modifying, and deleting elements, attributes, and text within a document.
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>
<p>This is a paragraph.</p>
</body>
</html>
JavaScript (script.js)
javascript
Copy code
document.getElementById('changeTitle').addEventListener('click', function() {
});
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')
o document.createElement('tag')
o parentElement.appendChild(newElement)