一、方法获取属性(上课笔记)
小注意点 可以在标签上自定义标签属性名
格式:data-xxxxx
自定义标签的获取
1.通过方法 getAtribute('key') 获取
2通过属性获取 标签.dataset.price
//注意 自定义属性不能直接用元素点(box1.name)的方式去获取,要先获取dataset属性
下面是案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- data-xxxx :自定义属性 -->
<div id="box" name="para" class="main" data-index="1" data-price="99.88">盒子</div>
<script>
var box1= document.querySelector('#box');
console.log(box1)
//可以获取元素的属性和方法
console.dir(box1);
// .attributes 获取指定原素上的所有属性
console.log(box1.attributes);
//.getAttribute('key') 通过方法获取标签上的属性
console.log(box1.getAttribute('id'));
//setAttribute('key','value') 添加和修改标签的属性
box1.setAttribute('class','qwe');
//removeAttribute('key')移除标签的属性
box1.removeAttribute('name');
//自定义属性的获取 (标签上的data-)
//注意 自定义属性不能直接用元素点(box1.name)的方式去获取,要先获取dataset属性
console.log(box1.getAttribute('data-index'));
console.log(box1.dataset.price);
console.log(box1.dataset.index);
</script>
</body>
</html>