Skip to content

DOM HTML

JavaScript HTML DOM:改变 HTML 内容和属性

Section titled “JavaScript HTML DOM:改变 HTML 内容和属性”

HTML DOM (文档对象模型) 允许 JavaScript 与 HTML 元素进行动态交互并修改其内容和结构。

使用 innerHTML 和 textContent 改变 HTML 内容

Section titled “使用 innerHTML 和 textContent 改变 HTML 内容”

改变 HTML 元素内容最常用的方法是使用其 innerHTML 或 textContent 属性。

The innerHTML property gets or sets the HTML markup contained within an element. When setting innerHTML, the browser parses the provided string as HTML.

示例:改变 <p> 元素的内容。

<!-- HTML -->
<p id="myParagraph">This is the original text.</p>
<script>
const paragraph = document.getElementById("myParagraph");
if (paragraph) {
paragraph.innerHTML = "**This is new, bold text!** And some <em>italic text</em>.";
}
</script>

**安全警告:**在使用来自用户或不受信任源的内容设置 innerHTML 时务必小心。如果内容包含恶意脚本,可能导致跨站脚本攻击 (XSS) 漏洞。在使用 innerHTML 渲染用户输入之前,务必对其进行清理/净化(sanitize)。

The textContent property gets or sets the text content of an element and its descendants. It treats the provided string as plain text, so any HTML tags will be rendered as literal text, not parsed as HTML. This makes it safer for displaying user-provided text.

示例:安全地改变 <h1> 元素的内容。

<!-- HTML -->
<h1 id="mainHeader">Old Header</h1>
<script>
const header = document.getElementById("mainHeader");
if (header) {
// 如果文本来自用户,使用 textContent 更安全
header.textContent = "New, Safe Header (even if it had <h1>tags</h1>)";
}
</script>

解释:

  • HTML 文档包含一个元素(例如,<p id="myParagraph"> 或 <h1 id="mainHeader">)。
  • 我们使用 document.getElementById() 获取该元素的引用。
  • 然后 JavaScript 改变其 innerHTML 或 textContent 属性。

JavaScript 也可以改变 HTML 属性的值。

直接属性访问(针对常见属性)

Section titled “直接属性访问(针对常见属性)”

对于许多标准的 HTML 属性,你可以直接将它们作为 DOM 元素对象的属性来访问。

element.attributeName = newValue;

示例:改变 <img> 元素的 src 属性和 <a> 元素的 href 属性。

<!-- HTML -->
<img id="myImage" src="old-image.jpg" alt="An image">
<a id="myLink" href="old-link.html">Old Link</a>
<script>
const image = document.getElementById("myImage");
if (image) {
image.src = "new-image.png";
image.alt = "A new, updated image";
}
const link = document.getElementById("myLink");
if (link) {
link.href = "new-link.html";
link.target = "_blank"; // Add a new attribute
}
</script>

For any attribute (including custom data-* attributes or attributes whose names might conflict with element properties), it’s more robust to use setAttribute() and getAttribute().`

element.setAttribute('attributeName', 'newValue'); const currentValue = element.getAttribute('attributeName');

示例:使用 setAttribute 和 getAttribute。

<!-- HTML -->
<div id="customDiv" data-info="initial info">Some content</div>
<script>
const divElement = document.getElementById("customDiv");
if (divElement) {
// 设置标准属性
divElement.setAttribute("class", "highlighted");
// 设置自定义数据属性
divElement.setAttribute("data-info", "updated information");
// 获取属性值
const currentInfo = divElement.getAttribute("data-info");
console.log("Current data-info:", currentInfo); // 输出: updated information
// 对于 data-* 属性,你也可以使用 dataset 属性:
// divElement.dataset.info = "updated via dataset";
// console.log(divElement.dataset.info);
}
</script>

document.write(htmlString) 直接写入 HTML 文档流。虽然它可能看起来是一种添加内容的简单方法,但它有显著的缺点:

  • 如果在 HTML 文档完成加载后使用,document.write() 将覆盖整个文档。 这通常是不可取的。
  • 对于大多数动态内容生成而言,它通常被视为一种遗留做法(legacy practice)。
  • 它会对性能产生负面影响,并且比有针对性的 DOM 操作更难管理。

示例(仅用于演示,通常在页面初始加载期间):

<!DOCTYPE html>
<html>
<head>
<title>Document.write Test</title>
</head>
<body>
<h1>Content Before Write</h1>
<script>
// 如果在页面解析期间使用(即完全加载之前),通常是可以的。
document.write("<p>Content written by JavaScript at " + new Date() + "</p>");
</script>
<p>Content After Write (if write doesn't overwrite everything)</p>
</body>
</html>
<!--
如果你的 document.write() 从事件处理程序(例如,按钮点击)调用 *after* the page loads,
它将擦除当前页面并用新内容替换。
-->

最佳实践: 避免在页面加载后使用 document.write() 来修改内容。请改用 innerHTML、textContent、appendChild() 等方法,或框架特定的技术。

有关 DOM 操作的更多详细信息,请查阅 MDN Web Docs 上的 DOM 文档。