JS-DOM属性操作和ECMAScript属性操作

本文详细讲解了JavaScript中DOM元素属性的操作,包括标准属性获取、设置、删除以及自定义data-*属性的使用,展示了ECMAScript和DOM操作的区别,并讨论了如何在innerHTML影响下保持特定属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值