getAttribute(name)
引數 name 表示屬性名稱。<div id="red">紅盒子</div> <div id="blue">藍盒子</div> <script> var red = document.getElementById("red"); //獲取紅色盒子 console.log(red.getAttribute("id")); //顯示紅色盒子的id屬性值 var blue = document.getElementById("blue"); //獲取藍色盒子 console.log(blue.getAttribute("id")); //顯示藍色盒子的id屬性值 </script>
var red = document.getElementById("red"); console.log(red.id); var blue = document.getElementById("blue"); console.log(blue.id);
<label id="label1" class="class1" for="textfield">文字方塊: <input type="text" name="textfield" id="textfield" /> </label> <script> var label = document.getElementById("label1"); console.log(label.className); console.log(label.htmlFor); </script>
<div id="red" class="red blue">紅盒子</div> <script> //所有類名生成的陣列 var classNameArray = document.getElementById("red").className.split(" "); for (var i in classNameArray) { //遍歷陣列 console.log(classNameArray[i]); //當前class名 } </script>