Course Content
Advanced JavaScript Mastery
Advanced JavaScript Mastery
What is the DOM?
Now that we've covered JavaScript classes let's switch our focus to the Document Object Model (DOM), which is the interface that allows us to manipulate web pages. The next section will explore how JavaScript interacts with the DOM to create dynamic, interactive content.
Think of the DOM like a family tree. Each element in the document is like a family member, connected by relationships - parents, children, and siblings.
In the DOM, elements, attributes, and text are called nodes, and these nodes are arranged hierarchically, just like family members in a family tree. Some nodes are parents with children, while others are siblings.
The Relationship Between HTML and the DOM
When a browser loads an HTML document, it reads the HTML code and builds a corresponding DOM tree. HTML provides the static structure of the webpage, while the DOM is the live, dynamic representation that JavaScript can manipulate.
- HTML defines the initial family tree structure of who is connected to whom, but it is static and doesn't change on its own;
- The DOM is the family tree in real-time, and it can be changed. New members (elements) can be added or removed, and relationships (parent-child, siblings) can be updated by JavaScript.
For example:
This HTML creates a basic family tree with an <html>
node as the parent, and the <head>
and <body>
nodes as its children. Within the body, <h1>
and <p>
are siblings.
This structure is the DOM's live, interactive version of the HTML, where JavaScript can manipulate relationships between nodes (family members).
How JavaScript Interacts with the DOM
JavaScript can access and manipulate the DOM to make changes to the family tree in real-time. You can add new members, remove existing ones, or change their information.
- Accessing Family Members: Just like you can find a specific person in a family tree, JavaScript can access individual nodes in the DOM using methods like
document.getElementById()
ordocument.querySelector()
; - Changing Information: Once a family member is accessed, their details can be updated. For example, JavaScript can change the text content or attributes of an element using properties like
innerHTML
ortextContent
; - Modifying Relationships: JavaScript can also add new family members to the tree or remove them. This is done by manipulating the DOM structure with methods like
appendChild()
orremoveChild()
.
Example
Consider this HTML:
Using JavaScript, we can change the text of the paragraph, just like updating the name of a family member:
After running the JavaScript code, the family tree (DOM) is updated, and the text of the paragraph changes from "Hello, World!" to "Hello, JavaScript!"
index
index
index
Thanks for your feedback!