- <!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>
- </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>
来源: http://www.bubuko.com/infodetail-3333382.html