js获取属性值,自定义属性,修改移除属性值
补充:由于不清楚一些属性是内置属性还是自定义属性 所以h5规定 自定义属性使用date-开头作为属性并赋值
案例1:
<body>
<div date-index="1"></div>
</body>
<script>
var div = document.querySelector(div);
console.log(div.getAttribute(date-index)); //打印为1
</script>
注:如果是自定义属性(自己给的属性)建议使用element.getAttribute(属性) 或者,如果是元素本身自带属性(如id),就使用element.属性
一.获取属性值
element.属性
获取内置属性(元素本身自带的属性
element.getAttribute(属性) //get 得到获取 attribute 属性
主要获得自定义属性 程序员自己添加的属性 被称为自定义属性
案例:获取div盒子属性的id 比如index=‘1’ 就是我们i自己定义的属性
<body>
<div id="demo" index="1"></div>
<script>
var div = document.querySelector(div);
console.log(div.id);
console.log(div.getAttribute(id));
console.log(div.getAttribute(index));
</script>
</body>
二.自定义属性 设置属性值
element.属性 = ‘值’;
案例1:修改属性id
<body>
<div id="demo" index="1"></div>
<script>
var div = document.querySelector(div);
div.id = text; //设置内置属性值
</script>
</body>
案例2:修改元素的类名 使用className
<body>
<div id="demo" index="1" class="box"></div>
<script>
var div = document.querySelector(div);
div.id = text; //设置内置属性值
div.className = boxs; //修改类名
</script>
</body>
element.setAttribute(属性, 值);
案例:修改自定义属性的值 index和class都是自己定义的属性
<body>
<div id="demo" index="1" class="box"></div>
<script>
div.setAttribute(index, 2);
div.setAttribute(class, nav);
</script>
</body>
三.移除属性值
element.removeAttribute(属性);
案例:比如不想要index了 移除index属性
<body>
<div id="demo" index="1" class="box"></div>
<script>
var div = document.querySelector(div);
//移除属性
div.removeAttribute(index)
</script>
</body>
上一篇:
IDEA上Java项目控制台中文乱码
