JavaScript编程
Completion requirements
修改 HTML 元素或 DOM 节点
在这页中,我们展示了如何修改 HTML 元素的两个不同方面:
- 元素的内容(通常只有一个内容,或者没有)
- 元素的属性(可能有多个属性)
请注意,内容和属性是两个不同的概念。
HTML 元素的结构
<!-- 一般形式: -->
<element_name attribute_name="attribute_value">element 的内容</element_name>
<!-- 具体示例。'href' 是属性,'Visit IANA...' 是内容。 -->
<a href="https://www.example.com">Visit IANA's example domain.</a>
示例页面
我们使用以下 HTML 示例页面来展示不同的修改方式。
<!DOCTYPE html>
<html>
<head>
<script>
function show() {
"use strict";
// ...
}
</script>
</head>
<body id="body" style="margin:2em">
<p id="p1" style="background: aqua">A blue paragraph</p>
<svg id="svgSrc" width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="25" fill="green"/>
</svg>
<p />
<a id="refToSomewhere" href="https://www.example.com">Visit IANA's example domain.</a>
<p />
<button id="buttonShow" onclick="show()">Start</button>
</body>
</html>
点击按钮会调用 show
函数,展示各种修改示例。
修改内容
我们用一个段落(p
元素)为例。要修改它的内容,只需将新的文本赋值给其 innerHTML
属性。
function show() {
"use strict";
const elem = document.getElementById("p1");
elem.innerHTML = "New text in the paragraph.";
}
或者,你可以用不同的 HTML 元素来做同样的事情,比如改变 SVG 图形的内容。
function show() {
"use strict";
const elem = document.getElementById("svgSrc");
elem.innerHTML = "<rect width='80' height='40' fill='blue'/>";
}
由于新的文本是 HTML 代码,你可以“误用”此方法来添加子节点。
function show() {
"use strict";
const elem = document.getElementById("p1");
elem.innerHTML = "New text in the paragraph.<p>next P</p><p>and even one more P</p>";
}
该脚本插入了两个新的段落,但它们并没有位于第一个段落之后,而是被包含在第一个段落内部。
<p id="p1">New text in the paragraph
<p>next P</p>
<p>and even one more P</p>
</p>
修改属性
修改属性的语法通常如下:
element_name.attribute_name = "new value";
// 或者:
element_name.setAttribute("attribute_name", "new value");
例如,HTML 元素 <a>
有一个 href
属性:
<a id="refToSomewhere" href="https://www.example.com">...</a>
你可以通过以下代码修改 href
属性:
function show() {
"use strict";
const elem = document.getElementById("refToSomewhere");
elem.href = "https://en.wikibooks.org";
elem.innerHTML = "Link changed";
}
首先,我们定位元素,然后通过修改 href
属性(以及 innerHTML
)来更新它。
以下示例修改了 img
元素的 src
属性和 button
元素的 value
属性:
<!-- HTML -->
<img id="imgOne" src="myPicture.jpg">
<input id="buttonOne" value="I'm a button!">
<!-- JavaScript -->
document.getElementById("imgOne").src = "otherPicture.jpg";
const b = document.getElementById("buttonOne");
b.value = "I'm a changed button";
使用 setAttribute()
修改属性
属性的修改也可以通过 setAttribute
函数来完成。
function show() {
"use strict";
const elem = document.getElementById("refToSomewhere");
elem.setAttribute("href", "https://en.wikibooks.org");
elem.innerHTML = "Link changed";
}
参考资料
Last modified: Monday, 13 January 2025, 3:10 PM