<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>属性操作</title>
</head>
<body>
<div id="box" class="box" test="test" data-test="ts">div标签
<div>mydiv</div>
</div>
<script>
// . [],ECMAScript 的属性操作
/*
- el.attributes 元素所有属性的集合
- el.getAttribute("attr") 获取属性
- el.setAttribute("attr","val") 设置属性
- el.removeAttribute("attr") 移出属性
- el.hasAttribute("attr") 判断是否有这个属性
*/
{
let box = document.querySelector("#box");
// 合法属性:w3c 规定的元素的属性,都存到这个对象中
console.dir(box); //不包含test属性
console.log(box.attributes); //包含test属性
console.log(box.getAttribute("class")); //打印:box
console.log(box.setAttribute("testing","测试中")); //删除属性,返回值为undefined
console.log(box.removeAttribute("class")); //删除属性,返回值为undefined
console.log(box.hasAttribute("testing")); //打印:true
console.log(box.test); //打印:undefined ECMAScript写法不能获取这种属性
}
{
let box = document.querySelector("#box");
box.index = 0; // ECMA 的属性操作,操作的是对象,具体的数据存在内存中,可以存储各种类型数据
box.setAttribute("test1",0); // DOM 的属性操作,值是存在文档中,类型只能是字符串,不是字符串的话,也会被转成字符串
console.log(typeof box.index); //打印:number
console.log(typeof box.getAttribute("test1")); //打印:string
console.log(box.test1); //打印:undefined ECMAScript写法不能获取这种属性
console.log(box.getAttribute("index")); //打印:null 在内存中,获取不到
}
{
let box = document.querySelector("#box");
let div = box.children[0];
div.index = 1;
div.setAttribute("test1","test1");
box.innerHTML = box.innerHTML;
console.log(box.children[0].index); //打印:undefined
console.log(box.children[0].getAttribute("test1")); //打印:test1
// 只要操作了innerHTML 元素的所有子元素上,存在内存中的事件和相关的属性都会丢失。如果希望元素的某些属性在操作了父级的innerHTML 之后,还存在就把这个属性加在DOM中
}
//自定义属性
{
let box = document.querySelector("#box");
box.dataset.test = "tested";
console.log(box.dataset.test); //打印:tested
}
</script>
</body>
</html>