Explain HTML DOM with examples
DOM stands for Document Object Model. It is a programming interface for web documents, which represents the structure of HTML or XML documents as a tree of objects that can be manipulated programmatically. Here's a brief explanation with examples:
1. Understanding DOM Structure
Consider this simple HTML structure:
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<div id="container">
<h1>Hello, DOM!</h1>
<p>Welcome to the Document Object Model.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</body>
</html>
2. Accessing Elements
In JavaScript, you can access elements of this HTML document using DOM methods. For example:
// Accessing the <h1> element
const heading = document.querySelector('h1');
console.log(heading.textContent); // Outputs: Hello, DOM!
// Accessing the <ul> element
const list = document.querySelector('ul');
console.log(list.children.length); // Outputs: 3 (number of <li> elements)
3. Modifying Elements
You can modify the content, style, or attributes of elements dynamically:
// Changing text content of <h1>
heading.textContent = 'DOM Manipulation Example';
// Adding a new <li> element to the <ul>
const newItem = document.createElement('li');
newItem.textContent = 'Item 4';
list.appendChild(newItem);
// Changing CSS style of an element
heading.style.color = 'blue';
4. Event Handling
DOM also facilitates event handling. You can attach event listeners to elements to respond to user interactions:
// Adding a click event listener to <button>
const button = document.querySelector('button');
button.addEventListener('click', function() {
alert('Button clicked!');
});
Benefits of DOM
- Dynamic Updates: Allows dynamic updating of document content.
- Platform Independence: Provides a platform-independent interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents.
- Event Handling: Enables interaction with user actions like mouse clicks, keyboard input, etc.
Published on: Jul 08, 2024, 03:19 AM