1. 自定义属性的操作
1.1 获取属性值
- element . 属性 获取属性值;(元素本身自带的属性)
- element . getAttribute( ' 属性 ' );(主要获取自定义的属性(标准))
1.2 设置属性值
-
element.属性='值'
-
element.setAttribute('属性','值')
1.3 移除属性
- removeAttribute('属性')
<body>
<div id="demo" index='12' class="nav"></div>
<script>
var div = document.querySelector('div');
// 1. 获取元素的属性值
// (1)element . 属性 如果是原有的属性可以直接写这个
console.log(div.id); //demo
// (2) element . getAttribute( ' 属性 ' ); 程序员自己添加的属性称为自定义属性 index
console.log(div.getAttribute('id')); //demo
console.log(div.getAttribute('index')); //12
// 2.设置元素属性值 (记住class比较特殊)
// (1)element.属性='值'
div.id = 'text';
div.className = 'navs'; //也可以这样直接把class的nav改为navs
console.log(div.id); //text
console.log(div.className); //navs
// (2) element.setAttribute('属性','值') 主要针对于自定义属性
div.setAttribute('index', '11');
console.log(div.getAttribute('index')); //11
div.setAttribute('class', 'footer');
console.log(div.getAttribute('class')); //footer
// 3.移除属性 removeAttribute('属性')
div.removeAttribute('index'); //index属性被移除
</script>
</body>