getAttribute setAttribute

本文介绍了一个简单的DOM操作示例,演示了如何使用JavaScript的getAttribute()和setAttribute()方法来获取和设置HTML元素的属性值。具体来说,通过一个按钮点击事件触发样式更改,实现了元素样式的动态切换。

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"));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值