1. 获取和修改元素内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Example</title>
</head>
<body>
<h1 id="myHeading">Hello, DOM!</h1>
<script>
// 获取元素的内容
var headingElement = document.getElementById("myHeading");
var headingContent = headingElement.innerHTML;
console.log("Original content: " + headingContent);
// 修改元素的内容
headingElement.innerHTML = "Updated content";
console.log("Updated content: " + headingElement.innerHTML);
</script>
</body>
</html>
2. 创建新元素和添加到文档:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Example</title>
</head>
<body>
<div id="myContainer"></div>
<script>
// 创建新元素
var newParagraph = document.createElement("p");
// 设置元素的文本内容
newParagraph.textContent = "This is a new paragraph.";
// 获取容器元素
var container = document.getElementById("myContainer");
// 将新元素添加到文档中
container.appendChild(newParagraph);
</script>
</body>
</html>
3. 添加事件处理程序:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Example</title>
</head>
<body>
<button id="myButton">Click me!</button>
<script>
// 获取按钮元素
var myButton = document.getElementById("myButton");
// 添加点击事件处理程序
myButton.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
</body>
</html>
这些实例演示了如何使用 HTML DOM 对象来访问和操作 HTML 文档。通过获取元素、修改内容、创建新元素、添加事件处理程序等操作,你可以实现丰富的交互式网页。 HTML DOM 是在 JavaScript 和 HTML 之间建立交互的关键。
转载请注明出处:http://www.pingtaimeng.com/article/detail/12849/JavaScript