通过 HTML DOM,JavaScript 能够访问 HTML 文档中的每个元素,并且可以修改这些元素的属性和文本值 修改 HTML = 改变元素、属性、样式和事件
修改 HTML DOM 意味着许多不同的方面:
innerHTML 插入文本或者修改元素的文本值
<body>
<h1>DOM HTML 修改</h1>
<p id="p1"></p>
<p id="p2">hello</p>
<script>
//给第一个p标签加文本节点
document.getElementById('p1').innerHTML = 'hello world!';
//修改第二个p标签文本值
document.getElementById('p2').innerHTML = 'world!';
</script>
</body>也可以用innerHTML 获取元素的文本值
<p id="p2">hello</p>
<script>
p2 = document.getElementById('p2');
console.log(p2.innerHTML) // hello
</script>元素的属性获取和设置 | 方法 | 描述 | | ———————————- | ——————————————— | | element.attributes | 返回一个元素的属性数组 | | element.getAttribute() | 返回指定的属性值。| | element.setAttribute() | 设置或者改变指定属性并指定值。| | element.hasAttribute() | 如果元素中存在指定的属性返回 true,否则返回false。| | element.hasAttributes() | 如果元素有任何属性返回true,否则返回false。 | | element.removeAttribute() | 从元素中删除指定的属性 |
attributes 返回一个元素的属性数组
<p id="p2" class="text-center">hello</p>
<script>
p2 = document.getElementById('p2');
console.log(p2.attributes) // NamedNodeMap {0: id, 1: class, id: id, class: class, length: 2}
console.log(p2.attributes["id"]) // 取值 id="p2"
console.log(p2.attributes["class"]) // 取值 class="text-center"
</script>element.getAttribute()返回指定的属性
<p id="p2" class="text-center">hello</p>
<script>
p2 = document.getElementById('p2');
console.log(p2.attributes) // NamedNodeMap {0: id, 1: class, id: id, class: class, length: 2}
console.log(p2.getAttribute('id')) // 取值 p2
console.log(p2.getAttribute('class')) // 取值 text-center
</script>setAttribute()设置或者改变指定属性并指定值
<p id="p2" class="text-center">hello</p>
<script>
p2 = document.getElementById('p2');
console.log(p2.attributes) // NamedNodeMap {0: id, 1: class, id: id, class: class, length: 2}
p2.setAttribute('class', 'text-info') // 设置class="text-info"
p2.setAttribute('title', 'hello') // 设置title="hello"
console.log(p2.attributes) // NamedNodeMap {0: id, 1: class, 2: title, id: id, class: class, title: title, length: 3}
</script>通过修改元素的style 属性修改css样式
<p id="p2" class="text-center">hello</p>
<script>
document.getElementById("p2").style.color="red";
document.getElementById("p2").style.fontSize="40";
</script>点击元素后修改元素的文本值,以及css样式
<p id="p2" class="text-center" onclick="myFunc()">点我看看</p>
<script>
function myFunc() {
p2 = document.getElementById("p2");
p2.innerHTML = '你刚才点我了';
p2.style.color="red";
p2.style.fontSize="40";
p2.style.background="blue";
}
</script>点击前

点击后

2022年第 11 期《python接口web自动化+测试开发》课程,6月5号开学!
2022年第 1 期《Python 测试平台开发》课程
《JMeter 性能测试实战》课程6月15号开学