How does the Document Object Model (DOM) work in a web browser? Explain how JavaScript can manipulate the DOM to update content dynamically. Provide a simple example of adding and removing elements from the DOM. Focus on: Basic DOM structure, methods like getElementById, appendChild, removeChild, and event handling.
The Document Object Model (DOM) is a hierarchical representation of a webpage’s content, structured as a tree of objects. Each element, attribute, and text in HTML becomes a node in this tree, allowing programs to dynamically access and update the page’s content, structure, and style.
JavaScript interacts with the DOM to manipulate these elements. For instance, the `getElementById` method retrieves an element by its ID, allowing direct manipulation.
Example:
“`html
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>
<div id=”container”>
<p id=”paragraph”>Hello, World!</p>
</div>
<button id=”addButton”>Add Element</button>
<button id=”removeButton”>Remove Element</button>
<script>
// Add new element
document.getElementById(‘addButton’).addEventListener(‘click’, () => {
const newElement = document.createElement(‘p’);
newElement.textContent = ‘New Paragraph’;
document.getElementById(‘container’).appendChild(newElement);
});
// Remove existing element
document.getElementById(‘removeButton’).addEventListener(‘click’, () => {
const container = document.getElementById(‘container’);
const paragraph = document.getElementById(‘paragraph’);
if (paragraph) {
container.removeChild(paragraph);
}
});
</script>
</body>
</html>
“`
Explanation:
1. **Basic DOM Structure**: The webpage contains a `div` with a paragraph and two buttons.
2. **getElementById**: Used to select elements (`addButton`, `removeButton`, `container`, `paragraph`).
3. **appendChild**: Adds a new paragraph to the `container` when the “Add Element” button is clicked.
4. **removeChild**: Removes the specified paragraph from the `container` when the “Remove Element” button is clicked.
5. **Event Handling**: `addEventListener` attaches click events to the buttons to perform the actions.
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a web page as a tree of objects, allowing programs to manipulate the page’s content, structure, and style.
When a web page is loaded, the browser parses the HTML and creates a DOM tree, with each element, attribute, and piece of text as a node.
The DOM tree would look like this:
– `html`
– `head`
– `title`: “Example”
– `body`
– `h1`: “Hello, World!”
– `p`: “This is a paragraph.”
This updates the DOM tree, and the browser reflects the change on the page.
For more information, you can refer to:
1. – [MDN Web Docs on DOM]