目录
JavaScript操作元素属性具有很多方式。这里主要辨析Element.属性名与Element.getAttribute()这两类方式的区别。
读取属性
Element.属性名:这个方法可以读取title,id,className等,注意属性名要按照javascript的格式来。特例:类名是className。
Element.getAttribute():这个方法同样是读取属性,但是略有不同。方法的参数是字符串,字符串内容是属性名。获取类名时直接使用class作为参数。当参数对应的属性不存在时返回null。
写入属性
Element.属性名=“属性值”:这个方法写入行内样式。当设置的样式不符合规范时会默认设置失败,不会报错。
Element.setAttribute("属性名",“属性值”):这个方法具有两个字符串参数。第一个参数是属性名,第二个参数是属性值。这个方法不同于上面的方法的是:它自定义的属性,可以出现在行内。而第一个方法设置的自定义属性只能默认设置失败,不会出现在行内。
使用setAttribute方法时针对类名直接使用class,而不是className。避免设置自定义属性className。
移除属性
Element.属性名=“”,可以将其设置为空字符串。这样做在html文档中对应元素只会留下相应的属性名,没有取值。
Element.removeAttribute("属性名"):这个方法接受一个属性名字符串,可以删除属性,不同点在于不会在html文档中留下属性名,删除比较彻底。针对自定义属性也可以删除。
检测属性是否存在
Element.hasAttribute()方法接受一个表示属性名的字符串,返回一个布尔值。如果元素具有该属性就返回true,反之返回false。
注意:如果前面使用Element.属性名=“”的方式会在html文档中留下一个属性名,这会使得这个方法检测结果为真。
以下为笔者测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试</title>
<style>
#box{
width: 100px;
height: 100px;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="box" title="这是一个div" class="BB"></div>
<script>
var box=document.getElementById("box");
//读取操作
console.log(box.title);
console.log(box.className);
console.log(box.getAttribute("title"))
console.log(box.getAttribute("class"))//这里注意略有差别
//写入操作
box.title="这是第一次更换的title 1";
console.log(box.title)
box.setAttribute("title","这是第二次更换的title 2");
console.log(box.title);
box.index=12;
console.log(box.index);//不会出现在行内,但是可以输出
box.setAttribute("CCC","自定义属性");//出现在行内
// box.setAttribute("class","???");
//移除操作
box.className="";
box.title="";
box.CCC=""//无法删除自定义属性。CCC取值不变
box.removeAttribute("CCC");//成功删除自定义属性
//检测是否含有某属性
console.log(box.hasAttribute("title"));//返回为真
</script>
</body>
</html>
getAttributeNS
实际效果和getAttribute类似,但是多了一个参数。第一个参数可以是一个表示命名空间的字符串,第二个参数仍是属性名字符串。
在getAttributeNodeNS,getElementsByTagNameNS中也可以看到后面的NS后缀。对应命名空间name space的NS首字母。这些都是增加了命名空间选择的方法。
本次分享到此结束了,方法中还有一些getAttributeNode,getAttributeNames()等。并不常用,在此不多做介绍。本文若有错误或不足之处,欢迎指正。