将HTML集合转换为Javascript数组?

时间:2016-08-10 14:03:09

标签: javascript arrays html5

我是新手,试图学习w3c-dom,html-dom,刚刚完成了这个DOM-Introduction

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>DOM</title>
  </head>
  <body>
    <script type="text/javascript">
      var getByTag = function(selector) {
        // FIXME: Do more conditions -- Come Up with more non-verbose regex condition
        return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
      }
      var isHTMLCollection = function(data) {
        return data.toString() === '[object HTMLCollection]';
      }
      var toArray = function(c) {
        return Array.prototype.slice.call(c);
      }
      var getAllPs = getByTag('p');
      console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
      console.log(Array.isArray(getAllPs), 'isArray-1');
      console.log(getAllPs, 'getAllPs');
      var _arrayLike = toArray(getAllPs);
      console.log(Array.isArray(_arrayLike), 'isArray-2');
      console.log(_arrayLike.length, 'Array.length');
    </script>
    <p id="p1">
      First Para
    </p>
    <p id="p2">
      Second Para
    </p>
  </body>
</html>

在控制台上记录这个时,我只是一个空数组,当我试图将HTMLCollection转换为数组时。

注意:也尝试使用for循环。

附加控制台输出

Console-Chrome

1 个答案:

答案 0 :(得分:1)

是的,添加

  

document.addEventListener('DOMContentLoaded',function(){//代码的其余部分});

修复了问题

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>DOM</title>
  </head>
  <body>
    <script type="text/javascript">
      document.addEventListener('DOMContentLoaded', function() {
        var getByTag = function(selector) {
          // FIXME: Do more conditions -- Come Up with more non-verbose regex condition
          return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
        }
        var isHTMLCollection = function(data) {
          return data.toString() === '[object HTMLCollection]';
        }
        var toArray = function(c) {
          return Array.prototype.slice.call(c);
        }
        var getAllPs = getByTag('p');
        console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
        console.log(Array.isArray(getAllPs), 'isArray-1');
        console.log(getAllPs, 'getAllPs');
        var _arrayLike = toArray(getAllPs);
        console.log(Array.isArray(_arrayLike), 'isArray-2');
        console.log(_arrayLike.length, 'Array.length');
      });
    </script>
    <p id="p1">
      First Para
    </p>
    <p id="p2">
      Second Para
    </p>
  </body>
</html>

注意:Chrome控制台问题是,异步评估数组值。

感谢@somethinghere&amp; @trincot。