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