JS中获取元素的第二种方法

1.静态方法

  var oUl = document.getElementById('');

2.动态方法

  document.getElementsByTagName('');

 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 <script>
 7 /*
 8 #list {}        var oUl = document.getElementById('list');                            静态方法
 9 
10 li {}                    document.getElementsByTagName('li');                                    动态方法
11 #list li {} var aLi = oUl.getElementsByTagName('li');
12                             // aLi => [ li, li, li ]     元素的集合
13                             aLi.length                                3
14                             aLi[0]
15                             // 在用 TagNasme 的时候,必须要加上:[]
16 */
17 window.onload = function (){
18     //    var oUl = document.getElementById('list');
19     var oUl = document.getElementsByTagName('ul')[0];
20     var aLi = oUl.getElementsByTagName('li');
21     
22     // document.getElementsByTagName('li');
23     
24     // alert( aLi.length );
25 };
26 </script>
27 </head>
28 
29 <body>
30 
31 <ul id="list">
32     <li></li>
33     <li></li>
34     <li></li>
35 </ul>
36 
37 <ol>
38     <li></li>
39     <li></li>
40 </ol>
41 
42 </body>
43 </html>
示例代码
 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 
 7 <script>
 8 window.onload = function (){
 9     // document.title = 123;
10     // document.body.innerHTML = 'abc';
11     var aBtn = document.getElementsByTagName('input');
12     
13     // alert(aBtn.length);
14     
15     document.body.innerHTML = '<input type="button" value="按钮" /><input type="button" value="按钮" /><input type="button" value="按钮" />';
16     
17     // alert(aBtn.length);
18     aBtn[0].onclick = function (){ alert(1); };
19     aBtn[1].onclick = function (){ alert(1); };
20     aBtn[2].onclick = function (){ alert(1); };
21     
22     // 重复执行某些代码
23     // 每次执行的时候,有个数字在变化
24 };
25 </script>
26 
27 </head>
28 
29 <body>
30 </body>
31 </html>
小练习题
原文地址:https://www.cnblogs.com/123wyy123wyy/p/6901547.html