javascript-DOM(3)
阿新 • • 發佈:2017-05-16
play load attribute bsp dom -1 tag html har
1、元素屬性操作
a、oDiv.style.display = "block";
b、oDiv.style["display"] = "block";
c、DOM方式
DOM方式操作元素屬性
1)獲取:getAttribute(名稱)
2)設置:setAttribute(名稱,值)
3)刪除:removeAttribute(名稱)
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 9 var oInp = document.getElementById(‘text1‘); 10 11 //oInp.value = ‘123‘;//第一種方法 12 oInp[‘value‘] = ‘456‘;//第二種方法 13 14 }15 </script> 16 </head> 17 18 <body> 19 <input id="text1" type="text" /> 20 </body> 21 </html>
運行效果:
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload= function (){ 8 9 var oInp = document.getElementById(‘text1‘); 10 11 oInp.setAttribute(‘value‘,‘789‘);//設置屬性 12 13 alert(oInp.getAttribute(‘id‘)); //獲取屬性
//oInp.removeAttribute(‘value‘);刪除屬性
14 } 15 </script> 16 </head> 17 18 <body> 19 <input id="text1" type="text" /> 20 </body> 21 </html>
運行效果:
2、用className來選取元素
改變class為box的li元素的背景顏色
代碼:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 var oUl = document.getElementById(‘ul1‘); 9 var oLi = oUl.getElementsByTagName(‘li‘); 10 11 for(var i=0;i<oLi.length;i++){ 12 if(oLi[i].className == ‘box‘){ 13 oLi[i].style.background =‘green‘; 14 } 15 } 16 17 } 18 </script> 19 </head> 20 21 <body> 22 <ul id="ul1"> 23 <li>aaaaaa</li> 24 <li>bbbbbb</li> 25 <li class="box">cccccc</li> 26 <li>dddddd</li> 27 <li class="box">eeeeee</li> 28 <li>ffffff</li> 29 <li class="box">gggggg</li> 30 <li>hhhhhh</li> 31 </ul> 32 </body> 33 </html>
運行效果:
javascript-DOM(3)