The Document Object Model (DOM) is a structured representation of a webpage, allowing scripts and programs to dynamically access and update content, structure, and styles. When a browser loads a webpage, it creates a tree-like structure where each element (like headings, paragraphs, and images) is a node that can be manipulated. This is crucial for interactive web applications.
The DOM represents an HTML document as a hierarchical tree:
<!DOCTYPE html>
<html lang="en-us">
<head></head>
<body>
<header>HEADER</header>
<nav>NAV</nav>
<main>MAIN
<article>ARTICLE
<section>SECTION</section>
</article>
</main>
<footer>FOOTER</footer>
</body>
</html>
For example, if a website needs to update text dynamically without reloading the page, JavaScript can modify the DOM directly:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Example</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
</style>
</head>
<body>
<p id="message">Hello, World! π</p>
<button onclick="document.getElementById('message').textContent = 'Hello, Universe! π'">
Click Me π
</button>
</body>
</html>
- The
<p>
element has anid
ofmessage
. - When the button is clicked, JavaScript changes the text of the
<p>
element usingdocument.getElementById
. - The update happens instantly without requiring a page reload.
Using semantic elements enhances accessibility and maintainability. Below is an example that structures a navigation bar and a section with accessible, meaningful elements:
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<section>
<h1>Welcome to My Website</h1>
<p>This is a simple example of a responsive navigation bar using HTML and CSS.</p>
<!-- Contact Information -->
<h2>Contact Information</h2>
<address>
<p>R.S. Aakil</p>
<p>149c Maliga Road, Maligailadu</p>
<p>Phone: 076328945</p>
<p>Email: <a href="mailto:[email protected]">[email protected]</a></p>
</address>
</section>
<footer>
<p>Β© 2023 Your Website. All Rights Reserved.</p>
</footer>
This example ensures proper structure, accessibility, and usability by using <header>
, <nav>
, <section>
, <address>
, and <footer>
instead of generic <div>
elements. π―
This demonstrates how the DOM enables real-time content updates, making web applications more interactive and engaging. π