网站

JavaScript HTML DOM 元素内容

Element: setAttribute() 方法 | MDN

Element: classList 属性 | MDN

引入

JS 获取到元素之后,下一步通常就是修改它。

修改元素的内容、属性、样式、类名,这些都是 DOM 操作里最常见的场景。

正文

定义

定义

修改元素是通过元素对象提供的属性和方法,改变元素的文本、HTML 内容、属性值、样式和类名。

修改文本内容

textContent 用来获取或设置元素的纯文本内容。

<p id="msg">旧内容</p>
const msg = document.querySelector("#msg");
 
msg.textContent = "新内容";

页面上的文字会从”旧内容”变成”新内容”。

textContent vs innerHTML

textContent 只处理纯文本,写入的 HTML 标签会被当成普通文字显示。

innerHTML 会解析 HTML 标签,把标签渲染成元素。

<div id="box"></div>
const box = document.querySelector("#box");
 
box.textContent = "<b>加粗</b>";

页面显示的是纯文本 <b>加粗</b>,标签没有被解析。

box.innerHTML = "<b>加粗</b>";

页面显示的是加粗文字,<b> 标签被解析成了元素。

建议:如果只是修改文字,优先用 textContent,更安全。innerHTML 有 XSS 风险,不要在用户输入的场景下使用。

属性作用HTML 标签安全性
textContent设置纯文本不解析安全
innerHTML设置 HTML 内容解析有 XSS 风险

修改属性

直接属性访问

常用属性可以直接通过点语法读写。

<img id="pic" src="old.jpg" alt="图片">
<a id="link" href="https://example.com">链接</a>
const pic = document.querySelector("#pic");
const link = document.querySelector("#link");
 
console.log(pic.src);
console.log(link.href);
 
pic.src = "new.jpg";
link.href = "https://newsite.com";

常用的直接属性:

属性说明
element.id元素的 id
element.src<img><script><iframe>src
element.href<a><link>href
element.value<input><select><textarea> 的值
element.disabled表单元素是否禁用

setAttribute() / getAttribute() / removeAttribute()

对于不常用的属性,或者自定义属性,用这三个方法。

<button id="btn" data-id="101">按钮</button>
const btn = document.querySelector("#btn");
 
console.log(btn.getAttribute("data-id"));
 
btn.setAttribute("data-id", "202");
console.log(btn.getAttribute("data-id"));
 
btn.removeAttribute("data-id");
  • getAttribute(name):读取属性值
  • setAttribute(name, value):设置属性值,属性不存在则创建
  • removeAttribute(name):删除属性

例子:切换图片

<img id="pic" src="cat.jpg" alt="猫">
<button id="btn">换一张</button>
const pic = document.querySelector("#pic");
const btn = document.querySelector("#btn");
 
btn.addEventListener("click", function () {
  pic.src = "dog.jpg";
  pic.alt = "狗";
});

点击按钮后,图片会从猫换成狗。

修改样式

通过 element.style 可以直接修改元素的内联样式。

<p id="tip">提示文字</p>
const tip = document.querySelector("#tip");
 
tip.style.color = "red";
tip.style.fontSize = "20px";
tip.style.display = "none";

注意:CSS 里的 font-size 在 JS 中要写成驼峰命名 fontSizebackground-color 写成 backgroundColor

CSS 属性JS 写法
colorcolor
font-sizefontSize
background-colorbackgroundColor
margin-topmarginTop
border-radiusborderRadius
displaydisplay

例子:点击隐藏元素

<div id="box" style="width: 100px; height: 100px; background: lightblue;"></div>
<button id="btn">隐藏</button>
const box = document.querySelector("#box");
const btn = document.querySelector("#btn");
 
btn.addEventListener("click", function () {
  box.style.display = "none";
});

操作类名

直接用 style 修改的是内联样式,样式多了不方便维护。更好的方式是通过切换 class 来改变样式。

element.classList 提供了操作类名的方法。

<p id="text" class="normal">一段文字</p>
.normal {
  color: black;
}
.highlight {
  color: red;
  font-weight: bold;
}
const text = document.querySelector("#text");
 
text.classList.add("highlight");

执行后 <p>class 变成 "normal highlight",文字变红加粗。

classList 常用方法

方法作用
classList.add("className")添加类名
classList.remove("className")移除类名
classList.toggle("className")有则移除,无则添加
classList.contains("className")判断是否包含某个类名

add() 添加类名

text.classList.add("active");
text.classList.add("large", "bold");

可以同时添加多个类名。

remove() 移除类名

text.classList.remove("highlight");

toggle() 切换类名

text.classList.toggle("active");

如果已经有 active 就移除,没有就添加。非常适合做开关效果。

contains() 判断类名

if (text.classList.contains("active")) {
  console.log("已激活");
}

例子:切换暗色模式

<button id="themeBtn">切换主题</button>
body {
  background: white;
  color: black;
}
.dark {
  background: #222;
  color: white;
}
const themeBtn = document.querySelector("#themeBtn");
 
themeBtn.addEventListener("click", function () {
  document.body.classList.toggle("dark");
});

点击按钮,<body> 会在亮色和暗色之间切换。

特点

  • textContent 修改纯文本,innerHTML 可以写入 HTML
  • 常用属性可以直接用点语法读写,其他属性用 setAttribute() / getAttribute()
  • element.style 修改内联样式,CSS 属性名要转成驼峰命名
  • classList 是操作类名的最佳方式,比直接改 className 更安全
  • toggle() 很适合做开关类的交互效果
  • 修改样式优先用切换 class,而不是直接改 style

注意事项

  • innerHTML 写入的内容会被浏览器解析,如果内容是用户输入的,会有 XSS 攻击风险
  • textContent 不会解析 HTML,所以更安全
  • style 修改的是内联样式,优先级比 CSS 文件里的样式高
  • classList.add()classList.remove() 不会重复添加或删除已存在的类名
  • 修改 class 前要先确认 CSS 里已经定义了对应的类名

理解

可以把修改元素理解成”编辑一个对象”。

元素对象上挂着文本、属性、样式、类名这些信息,JS 拿到元素后,就可以一项一项地去改。

textContent 改文字,setAttribute() 改属性,style 改内联样式,classList 改类名。

我理解修改元素的重点是:先获取元素,再选择合适的方式修改对应的信息

改文字用 textContent,改少量样式用 style,改多组样式用 classList 切换类名。

引出

掌握了修改元素的方法后,可以继续学习 JS 创建和删除元素,了解怎么动态添加和移除页面元素。