Sathish
Sathish

Reputation: 2180

Convert a HTML Collection to Javascript Array?

I am a newbie, trying to learn w3c-dom, html-dom, just went through this 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>

While logging this on console, i got just an empty array, when i tried to convert the HTMLCollection to Array.

Note: Tried using for-loop also.

Attached the console output,

Console-Chrome

Upvotes: 0

Views: 3183

Answers (1)

Sathish
Sathish

Reputation: 2180

Yes, adding

document.addEventListener('DOMContentLoaded', function() { //rest of the code });

fixes the issue

<!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>

Note: Problem with chrome console is, array values are evaluated on asynchronously.


Thanks to @somethinghere & @trincot.


Upvotes: 1

Related Questions