DOM 方法
JavaScript - 与 HTML DOM 交互
Section titled “JavaScript - 与 HTML DOM 交互”The HTML DOM (Document Object Model) provides a programming interface for HTML documents. It represents the page structure as a tree of objects, allowing JavaScript to dynamically access and modify the content, structure, and style of a web page.
DOM 属性是你可以获取或设置的 HTML 元素的值(例如,element.textContent)。
DOM 方法是你可以对 HTML 元素执行的操作(例如,element.appendChild())。
DOM 编程接口
Section titled “DOM 编程接口”When an HTML document is loaded in a browser, it becomes a document object. This object is the entry point to the content of the page (the DOM tree). All HTML elements are defined as objects with their own properties and methods.
常见任务包括:
- 查找 HTML 元素。
- 改变 HTML 内容和属性。
- 改变 CSS 样式。
- 添加或删除 HTML 元素。
- 响应用户事件。
查找 HTML 元素
Section titled “查找 HTML 元素”To manipulate an HTML element, you first need to find it. JavaScript offers several methods:
1. document.getElementById(id)
Section titled “1. document.getElementById(id)”This is a classic and efficient way to find a single element by its unique id attribute.
const mainTitle = document.getElementById("main-title");if (mainTitle) { mainTitle.style.color = "blue";}2. document.querySelector(cssSelector)
Section titled “2. document.querySelector(cssSelector)”A powerful and versatile modern method that returns the first element within the document that matches the specified CSS selector(s).
// 查找第一个 <p> 元素const firstParagraph = document.querySelector("p");
// 查找 id 为 "contact-form" 的元素const contactForm = document.querySelector("#contact-form");
// 查找第一个 class 为 "highlight" 的元素const highlightedItem = document.querySelector(".highlight");
// 查找 id 为 "login-form" 的 <form> 内部的 <button>const loginButton = document.querySelector("form#login-form button.submit-btn");3. document.querySelectorAll(cssSelector)
Section titled “3. document.querySelectorAll(cssSelector)”Returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors. You can then iterate over this list.
const listItems = document.querySelectorAll("ul.product-list li");listItems.forEach(item => { item.style.fontWeight = "bold";});其他较旧的方法(现在直接使用较少,但了解一下有好处):
document.getElementsByTagName(tagName):返回一个实时的HTMLCollection,包含具有给定标签名的元素。document.getElementsByClassName(className):返回一个实时的HTMLCollection,包含具有给定类名的元素。
通常更倾向于使用 querySelector 和 querySelectorAll,因为它们与 CSS 选择器配合使用时更加灵活。
改变 HTML 内容
Section titled “改变 HTML 内容”获得元素引用后,您可以改变其内容:
1. element.textContent
Section titled “1. element.textContent”Gets or sets the text content of an element and its descendants. This is generally the safest and often most performant way to deal with text. It treats the content as plain text, not HTML.
const messageDiv = document.getElementById("message");if (messageDiv) { messageDiv.textContent = "Welcome, User!"; // 安全地设置文本}2. element.innerHTML
Section titled “2. element.innerHTML”Gets or sets the HTML markup contained within an element. Use this when you need to insert HTML structure. Be cautious: setting innerHTML with content from untrusted sources can lead to Cross-Site Scripting (XSS) vulnerabilities because it parses and executes the HTML, including any <script> tags.
const productInfo = document.getElementById("product-details");if (productInfo) { productInfo.innerHTML = "**Product Name:** Awesome Gadget <br> <em>Limited stock!</em>";}安全注意:在使用 innerHTML 将用户提供的数据插入到 DOM 中之前,务必进行净化或仔细验证。处理纯文本时,优先使用 textContent 以避免 XSS 风险。 |
|---|
修改元素属性
Section titled “修改元素属性”You can change HTML attributes directly as properties on the element object (for common attributes) or using setAttribute and getAttribute.
const myImage = document.getElementById("banner-image");if (myImage) { myImage.src = "new-image.jpg"; // 直接设置 'src' 属性 myImage.alt = "A new beautiful banner image";
// 使用方法 myImage.setAttribute("data-custom-info", "extra details"); console.log(myImage.getAttribute("data-custom-info"));
myImage.removeAttribute("title");}创建和添加元素
Section titled “创建和添加元素”You can dynamically create new HTML elements and add them to the DOM.
const list = document.getElementById("my-list");if (list) { // 创建一个新的 <li> 元素 const newItem = document.createElement("li");
// 设置其内容 newItem.textContent = "New item added dynamically!";
// 添加一个类用于样式设置 newItem.classList.add("list-item-dynamic");
// 将新的 <li> 追加到 <ul> 中 list.appendChild(newItem);}
// 其他添加元素的方法包括:// parentNode.insertBefore(newNode, referenceNode)// element.prepend(...nodes)// element.append(...nodes)// element.replaceWith(...nodes)Learning these DOM manipulation methods allows for rich, dynamic web applications where content can change without reloading the entire page.