DOM属性获取、设置、删除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>DOM属性获取、设置、删除</title>
    <!-- 
        e.getAttribute("id");获取元素e属性id的值,只要是已设置的属性都可以获取
        e.setAttribute("id","red");设置元素e属性id的值为red,也可以用来添加新属性
        e.removeAttribute("id");删除e元素的id属性

        切记:以上方法只对写在行内的属性有效
            正确姿势:e.setAttribute("style","color:red;background:grey");//或者id/class/name等;
            删除元素的属性同理,但e.removeAttribute("style");//只对行内样式有效
     -->
</head>
<body>
    <div id="p1" class="pp" align="center" 随便写个属性="随便写个值">我是什么颜色</div>
    <script>
        var a=document.getElementById("p1");
        console.log(a.id);//p1
        console.log(a.class);//undefined;无法直接获取class的值
        console.log(a.align);//center
        console.log(a.随便写个属性);//undefined;无法获取自定义的属性
        //e.getAttribute("")
        console.log(a.getAttribute("id"));//p1
        console.log(a.getAttribute("class"));//pp
        console.log(a.getAttribute("随便写个属性"));//随便写个值
        //e.setAttribute("属性","值")
        a.setAttribute("随便写个属性","我重新设置了一个属性");//页面中:随便写个属性="我重新设置了一个属性"
        a.setAttribute("style","background: red;font-style: italic;");//给元素a设置属性background-color,值为red
        //e.removeAttribute("要删除的属性")
        a.removeAttribute("align");//删除了元素a的align属性
    </script>
</body>
</html>

posted on 2019-12-15 21:58  loongw  阅读(1271)  评论(0编辑  收藏  举报

导航