JavaScript&jQuery.获取修改元素属性

获取修改元素属性

javaScript可以修改DOM节点属性。

操作属性的方法有:

方法 说明
getAttribute()

获取属性值

hasAttribute() 检查元素节点是否包含特定属性
setAttribute() 设置属性值
removeAttribute 从元素节点移除属性

修改属性

<!DOCTYPE html>
<html>
<head>
<title>元素属性</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css"
rel="stylesheet">
<style>
.color{
color:red;
}
.other-color{
color:blue;
}
</style>
</head>
<body>
<h1>修改属性</h1>
<table class="table">
<ul>
<li class="color">油条</li>
<li class="color" id="b">包子</li>
<li class="color">米饺</li>
<li class="color" id="d"><a>鱼粉</a></li>
</ul>

<script>
var EL = document.getElementById('b');
if(EL.hasAttribute('class')){
alert(EL.getAttribute('class'));
EL.setAttribute('class','other-color');
}

</script>
</body>
</html>


删除属性

<!DOCTYPE html>
<html>
<head>
<title>删除属性</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.color{
color:red;
}
.other-color{
color:blue;
}
</style>
</head>
<body>
<ul id="ul">
<li class="color">油条</li>
<li class="color" id="f">包子</li>
<li class="color" id="a">米饺</li>
<li class="color">鱼粉</li>
</ul>
<script>
var EL = document.getElementById('a');
if (EL.hasAttribute('class')) {
alert(EL.getAttribute('class'));
EL.setAttribute('class');
}
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/H97042/p/9274191.html