JavaScript in the Browser: DOM and Events Fundamentals:
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure, style, and content of a web page as a tree of objects and nodes, enabling dynamic manipulation of the document by programs. This capability allows languages like JavaScript to interact with and modify the content of a web page.
Key Points about the DOM
-
Tree Structure: The DOM represents an HTML document as a hierarchical tree structure of objects. Each HTML element (e.g.,
<div>
,<p>
,<h1>
) becomes an object node in this tree. -
Hierarchical Nature: It is hierarchical, with a single top-level object (the document object) branching out into other objects that represent elements, attributes, and text within the document.
- HTML Document Tree Representation in the DOM:
-
Language Agnostic: While commonly used with JavaScript, the DOM itself is not specific to any programming language. It can be accessed and manipulated by various languages such as JavaScript, Python, or Java.
Understanding the DOM is crucial for developers working with JavaScript to create interactive and dynamic web applications.
Selecting Elements
- By ID: To select an element by its ID attribute:
- By Class Name: To select elements by their class name (returns a collection):
- By Tag Name: To select elements by their tag name (returns a collection):
- By CSS Selector (Single Element): To select a single element using a CSS selector:
- By CSS Selector (Multiple Elements): To select multiple elements using a CSS selector (returns a collection):
Modifying Elements
- Changing Text Contents: To change the text content of an element:
- Changing HTML Contents: To change the HTML content of an element:
- Changing Attributes: To change an attribute of an element:
- Changing Styles: To change the CSS styles of an element: