本文主要是介绍几个常见的 JavaScript DOM 操作的案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 修改元素内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>修改内容</title>
</head>
<body>
<p id="myParagraph">原始内容</p>
<button οnclick="changeContent()">更改内容</button>
<script>
function changeContent() {
document.getElementById('myParagraph').innerText = '内容已更改!';
}
</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>添加元素</title>
</head>
<body>
<ul id="myList">
<li>项 1</li>
<li>项 2</li>
</ul>
<button οnclick="addItem()">添加项</button>
<script>
function addItem() {
const ul = document.getElementById('myList');
const li = document.createElement('li');
li.textContent = '新项';
ul.appendChild(li);
}
</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>删除元素</title>
</head>
<body>
<div id="container">
<p id="toDelete">这个段落将被删除。</p>
</div>
<button οnclick="removeElement()">删除元素</button>
<script>
function removeElement() {
const element = document.getElementById('toDelete');
element.remove();
}
</script>
</body>
</html>
4. 修改样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>修改样式</title>
</head>
<body>
<div id="myBox" style="width: 100px; height: 100px; background: red;"></div>
<button οnclick="changeStyle()">改变样式</button>
<script>
function changeStyle() {
const box = document.getElementById('myBox');
box.style.backgroundColor = 'blue';
box.style.width = '200px';
box.style.height = '200px';
}
</script>
</body>
</html>
这篇关于几个常见的 JavaScript DOM 操作的案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!