, etc.
Node: A basic unit in the DOM tree, which could be an element, text, or attribute.
DOM Tree: A hierarchical structure that represents the webpage as a tree of nodes. The root node is the document, and each HTML element is a node branching from it.
Example of DOM Representation:
For an HTML document like:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<div>
<p>The DOM for this document might look like this:<br>
</p>
<pre class="brush:php;toolbar:false">Document
├── html
├── head
│ └── title
└── body
└── div#content
├── h1
└── p
How JavaScript Uses the DOM:
-
Accessing Elements: JavaScript can select and access elements from the DOM using methods like document.getElementById() or document.querySelector().
let heading = document.getElementById("content");
-
Manipulating Elements: JavaScript can modify the content, attributes, or style of elements.
heading.innerHTML = "New Content";
heading.style.color = "red";
-
Event Handling: JavaScript can attach event listeners to DOM elements to respond to user actions like clicks, key presses, etc.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
-
Creating and Removing Elements: JavaScript can dynamically create new elements or remove existing ones.
const newElement = document.createElement("div");
document.body.appendChild(newElement);
Why the DOM is Important:
- It provides a way for JavaScript to interact with and manipulate the structure and content of a webpage.
- It allows for dynamic, interactive web pages without requiring a page reload (e.g., for updating the UI or handling user inputs).
DOM Methods:
Here are some commonly used DOM methods in JavaScript:
-
getElementById(): Selects an element by its ID.
-
querySelector(): Selects the first matching element using a CSS selector.
-
createElement(): Creates a new HTML element.
-
appendChild(): Adds a new child node to an element.
-
removeChild(): Removes a child node from an element.
-
setAttribute(): Sets an attribute on an element.
-
addEventListener(): Attaches an event handler to an element.
Example in Action:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<div>
<p>The DOM for this document might look like this:<br>
</p>
<pre class="brush:php;toolbar:false">Document
├── html
├── head
│ └── title
└── body
└── div#content
├── h1
└── p
In this example, the h1 element is selected, its content is updated, and a click event listener is attached to it. When the heading is clicked, an alert is shown.
The DOM is an essential concept for manipulating the structure of web pages dynamically with JavaScript, and it is fundamental to creating interactive web applications.
The above is the detailed content of What is DOM (Document Object Modle) in JavaScript. For more information, please follow other related articles on the PHP Chinese website!