获取自定义属性值

1.获取 属性值
element ?属性 获取属性值
element.getAttribute('属性')

区别:
element.属性 获取内置属性值(元素本身自带属性)
element.getAttribute('属性');主要获得自定义的属性(标准)我们程序员自定义的属性

复制代码
<body>
        <div id="demo" index="1"></div>
  </body>
  <script>
    let div = document.querySelector("div");
    // 1.获取元素的属性值
    // (1)element.属性
    console.log(div.id); //获取div的id名
    // (2)element.getAttribute('属性')  get得到获取attribute属性的意思
    //  我们程序自己添加的属性我们称为自定义属性 index
    console.log(div.getAttribute("id")); //获取div的id名
    console.log(div.getAttribute("index"));
    // 2.设置元素属性值
    // (1)element.属性='值'
    div.id = "test";
    div.className = "navs";
    // (2)element.setAttribute('属性','值');  主要针对于自定义属性
    div.setAttribute("index", 2);
    div.setAttribute("class", "footer"); //class特殊  这里面写的就是class 不是className
    // 3.移除属性 removeAttribute(属性)
    div.removeAttribute("index");
  </script>
复制代码

 

posted @   罗砂  阅读(402)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示