在HTML
中,一个元素会有很多属性,比如id
属性,class
属性,title
属性等等,如何操作这些呢?
一. getAttribute():
获取属性值
element.getAttribute(attributename)
返回元素的指定属性的值。
参数:元素的某个属性的名 (
id, className, title
)
<body>
<a id="id1" href="http://www.atguigu.com/" target="_blank">xyxyxy官网</a>.
<br />
<p>
<button onclick="myFunction()">点我获取超级链接的 id 属性值,tafget 属性值</button>
</p>
<script>
function myFunction() {
var a1 = document.getElementById("id1");
alert("id = " + a1.getAttribute("id") + "\ntarget = " + a1.getAttribute("target"));
}
</script>
</body>
二. setAttribute():
设置属性值
element.setAttribute(attributename,attributevalue)
作用:创建建或改变某个新属性。如果指定属性已经存在,则只设置该值。如果属性不存在,则创建该属性并设置属性值。
参数1:属性名
参数2:新的属性值
<body>
<input value="OK" >
<br/>
<button onclick="myFunction()">点我把上述文本框的 type 属性设置为 button 样式</button>
<script>
function myFunction() {
var inputs = document.getElementsByTagName("input");
//把input的 type属性设置为button
inputs[0].setAttribute("type", "button");
};
</script>
</body>
三. removeAttribute()
: 移除属性
element.removeAttribute(attributename)
- 参数:必需。规定要删除的属性的名称。
<body>
<input id="input1" type="button" value="点我可以转换我的状态" onclick="myFunction();">
<script>
function myFunction() {
var input1 = document.getElementById("input1");
var typeValue = input1.getAttribute("type");
if(typeValue){
input1.removeAttribute("type"); //如果type属性有值就把这个属性去掉
}else {
input1.setAttribute("type", "button"); //如果type属性不存就添加属性。
}
};
</script>
</body>
四. hasAttribute()
:判断是否具有这样的属性
element.hasAttribute(attributename)
- 参数:必须。判断指定的属性名是否存在。