js实现修改
使用 JavaScript 修改 DOM 元素
通过 JavaScript 可以动态修改 HTML 元素的属性、样式、内容等。以下是几种常见的修改方式:
修改元素内容
使用 innerHTML 或 textContent 修改元素的文本或 HTML 内容:
const element = document.getElementById("example");
element.innerHTML = "<strong>新内容</strong>"; // 支持 HTML
element.textContent = "纯文本内容"; // 仅文本
修改元素属性
使用 setAttribute 或直接访问属性修改:
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com"); // 修改 href
link.className = "new-class"; // 修改 class
link.style.color = "red"; // 修改内联样式
修改 CSS 样式
通过 style 对象修改元素的样式:
const box = document.getElementById("box");
box.style.backgroundColor = "blue";
box.style.fontSize = "20px";
动态添加或移除类
使用 classList 方法管理类名:
const button = document.querySelector("button");
button.classList.add("active"); // 添加类
button.classList.remove("inactive"); // 移除类
button.classList.toggle("highlight"); // 切换类
修改表单元素值
直接修改 value 属性:
const input = document.getElementById("username");
input.value = "新用户名";
修改多个元素
使用 querySelectorAll 遍历修改多个元素:
const items = document.querySelectorAll(".item");
items.forEach(item => {
item.style.color = "green";
});
使用事件监听动态修改
结合事件监听器实现交互式修改:
document.getElementById("btn").addEventListener("click", () => {
document.body.style.backgroundColor = "lightblue";
});
这些方法涵盖了常见的 DOM 修改需求,可根据具体场景选择合适的方式。






