JavaScript and the HTML DOM
Understanding the HTML DOM (Document Object Model)
When a web page is loaded, the browser generates a Document Object Model (DOM) for that page. The HTML DOM represents the structure of the page as a tree of objects.
The HTML DOM Tree
The DOM is visualized as a tree of objects, where each element, attribute, and piece of content in the HTML document is a node in this tree. This structure gives JavaScript the power to dynamically manipulate the HTML content and appearance.
Capabilities of JavaScript with the HTML DOM
With the HTML DOM, JavaScript can:
- Modify all HTML elements on the page.
- Change all HTML attributes.
- Update CSS styles for any element.
- Remove existing HTML elements and attributes.
- Add new HTML elements and attributes.
- Respond to existing HTML events.
- Create new HTML events.
What You Will Learn
In the upcoming chapters of this tutorial, you will explore:
- How to alter the content of HTML elements.
- How to change the CSS styles of HTML elements.
- How to respond to HTML DOM events.
- How to add and remove HTML elements.
What is the DOM?
The DOM is a standard defined by the W3C (World Wide Web Consortium). It is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
Parts of the W3C DOM Standard
The W3C DOM standard is divided into three parts:
- Core DOM: The standard model for all document types.
- XML DOM: The standard model for XML documents.
- HTML DOM: The standard model for HTML documents.
What is the HTML DOM?
The HTML DOM is a standard object model and programming interface for HTML. It defines:
- HTML elements as objects.
- Properties of all HTML elements.
- Methods to access all HTML elements.
- Events for all HTML elements.
In summary, the HTML DOM is a standard for manipulating HTML elements, allowing you to get, change, add, or delete elements on the web page.
Code Example: Changing HTML Content
Here's an example of how you can change the content of an HTML element using JavaScript and the DOM:
<!DOCTYPE html><html><head> <title>DOM
Example</title></head><body>
<h1 id="header">Original Heading
</h1> <button onclick="changeContent()">Change Content</button>
<script> function changeContent()
{ document.getElementById("header").innerHTML = "New Heading";
} </script></body></html>
In this example, clicking the button will trigger the changeContent function, which changes the text of the <pre style="display: inline"><h1></pre> element with the id header from "Original Heading" to "New Heading".