getAttribute()方法:通过元素节点的属性名称获取属性的值
elementNode.getAttribute(name)
elementNode:使用getElementById、getElementsByTagName()等方法获取到的元素节点;name:要想查询的元素节点的属性名字
setAttribute()方法:增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值
elementNode.setAttribute(name,value)
name:要设置的属性名;value:要设置的属性值,,如果把指定的属性设置为指定的值,如果不存在具有指定名称的属性,该方法将创建一个新的属性,setAttribute()方法只能通过元素节点对象调用函数
.redStyle{
width:200px;
height:100px;
background-color: red;
text-align: center;
line-height: 100px;
}
.blueStyle{
width:200px;
height:100px;
background-color: #2f6fad;
text-align: center;
line-height: 100px;
}
<div id="id" class="redStyle">liubbc</div>
<button onclick="changeColor()">change color</button>
<script>
function changeColor() {
document.getElementById("id").setAttribute("class", "blueStyle");
}
alert(document.getElementById("id").getAttribute("class"));
本文介绍了一个简单的DOM操作示例,演示了如何使用JavaScript的getAttribute()和setAttribute()方法来获取和设置HTML元素的属性值。具体来说,通过一个按钮点击事件触发样式更改,实现了元素样式的动态切换。
8860

被折叠的 条评论
为什么被折叠?



