本文主要介绍DOM中自定义属性的设置、获取及移除。自定义属性比较典型的应用是给元素添加一个“标签”,方便查找该元素或建立此元素同其他元素之间的联系。
1.setAttribute用于设置属性的值,若不存在该属性则进行创建
2.getAttribute用于获取相应属性的值
3.removeAttribute用于移除相应属性。(注:有时某些属性的值通过设置值的方式达不到效果,就可以进行移除)
<!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>Document</title>
</head>
<body>
<a href="http://www.baidu.com">百度</a>
<script>
var a = document.querySelector('a');
// 1.设置自定义属性(如果没有该属性,则创建)
a.setAttribute('index', 0);
a.setAttribute('selfDefine', 1);
// 2.获得自定义属性的值
console.log(a.getAttribute('index'));
console.log(a.getAttribute('selfDefine'));
// 3.移除自定义属性
a.removeAttribute('index');
</script>
</body>
</html>