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>
运行效果:
时间: 2024-10-10 04:15:39