dom对象
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 </head> 7 8 <body> 9 <div id="one"></div> 10 <input type="text" name="two" value="123" id="tow" > 11 <ul> 12 <li>1</li> 13 <li>2</li> 14 <li>3</li> 15 </ul> 16 <div class="four">1</div> 17 <div class="four">2</div> 18 <div class="four">3</div> 19 <div id="five">今天晴天</div> 20 <table border="1" cellpadding="0" cellspacing="0"> 21 </table> 22 <div id="a"> 23 24 </div> 25 26 27 28 </body> 29 </html> 30 <script type="text/javascript"> 31 //找到dom元素 32 /*document:文档 33 get :拿到,得到 34 element :元素 35 by :通过 36 通过id名找到元素**/ 37 var one = document.getElementById("one"); 38 //console.log("one"); 39 //通过name属性,找到元素 40 var two = document.getElementsByName("two"); 41 //通过标签名找到元素 HTMLcollection:集合 42 var three = document.getElementsByTagName("li"); 43 //document.write(three[0].innerHTML); 44 var four = document.getElementsByClassName("four"); 45 //console.log(four[1].innerHTML); 46 //操作dom元素 47 var five = document.getElementById("five"); 48 //five.innerHTML = "今天下雨了"; 49 //five.innerText = "今天<br>666"; 50 var tab = document.getElementsByTagName("table"); 51 var str = ""; 52 for(var i = 0;i<3;i++){ 53 str=str+"<tr>"; 54 for(var j=0;j<5;j++){ 55 str=str+"<td>周一</td>"; 56 }str = str+"</tr>"; 57 } 58 59 //tab[0].innerHTML = str; 60 //3.操作做表单的value 61 var inpt = document.getElementById("two"); 62 //alert(inpt.value); 63 //value = name
<ul>
<li>1<
>
<li>2<
>
<li>3<
>
<li>4<
>
<li>5<
>
</ul>
<li>1<
<li>2<
<li>3<
<li>4<
<li>5<
</ul>
var b = document.getElementById("a") //找到<div id=a>,然后定义给b var str = ""; //定义一个str空值 for(var i=0; i<1;i++){ //定义i为行变量,循环一次 str= str+"<ul>"; for(var c= 0;c<5;c++){ str= str+"<li>"+(c+1)+"</li>"; }str = str+"</ul>"; } b.innerHTML=str;
通过id取值
1 <div id="one">555</div> // 2 var a = document.getElementById("one"); //通过id one找到<div>,赋值给a 3 console.log(a.innerHTML); //输出a,不需要【】
通过name属性
<input type="text" name="two" value="123" id="tow" > var two = document.getElementsByName("two"); console.log(two[0].value); //value = name 传value的值
通过标签来寻找,通过标签名字来寻找
1 <ul> 2 <li>1</li> 3 <li>2</li> 4 <li>3</li> 5 </ul> 6 7 var a = document.getElementsByTagName("li") 8 //console.log(a[2].innerHTML)
通过class来寻找,直接控制,像id一样,class控制多个
1 <div class="four">1</div> 2 <div class="four">2</div> 3 <div class="four">3</div> 4 5 var a = document.getElementsByClassName("four"); 6 console.log(four[0].innerHTML)