0

How to I loop through the elements retrieved using document.getElementsByTagName(); as it's length is coming out to be 0 but still has elements.

Below is the JS code:

class HKPlayer
{
    constructor()
    {
        this.getPlayers();
        this.getPlayerAttributes();
    }
    getPlayers()
    {
        this.players = document.getElementsByTagName("HKPlayer");
    }
    getPlayerAttributes()
    {
        console.log(this.players);
    }
}
(function () {
    new HKPlayer();
})();

below is the html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HKPlayer Demo</title>
    <script src="dist/HKPlayer.js" type="text/javascript"></script>
</head>
<body>
    <HKPlayer type="video" theme="dark" src="assets/video/1.mp4"></HKPlayer>
    <br/>
    <HKPlayer type="video" theme="dark" src="assets/video/2.mp4"></HKPlayer>
</body>
</html>

The output is like:

enter image description here

enter image description here

I cannot loop through this.players as the array this.players array is empty. how do I do that.

Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
  • 1
    Is the DOM loaded at the point of execution? If not, it’s a dupe of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/q/14028959/4642212); otherwise, likely a dupe of [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/q/4057440/4642212). – Sebastian Simon Oct 04 '17 at 17:47

2 Answers2

1

You're executing your JS before the DOM is loaded.

Try wrapping this part of your code:

(function () {
    new HKPlayer();
})();

Inside this:

document.onreadystatechange = function()
{
    if(document.readyState === 'complete')
    {
        // Put your code that relies on a complete/ready DOM here.
    }
}

EDIT: As a response to the comment, no this is not 100% cross-browser, nor will it always work. If you want as much browser-support as possible, you'd most likely want to use the following methods:

document.addEventListener('DOMContentLoaded', fn, false);

with a fallback to:

window.addEventListener('load', fn, false )

or for older versions of IE:

document.attachEvent("onreadystatechange", fn);

with a fallback to:

window.attachEvent("onload", fn);

This is apparently how jQuery handles its $(document).ready(). More information about this can be found here.

0

Array is not empty it has length and two items as i saw on your attached picture, i think you can access this.player.length and this.player[0] in getPlayerAttributes function. If you

Ferhat BAŞ
  • 797
  • 7
  • 12
  • this.players.length returns 0 – Shakti Phartiyal Oct 04 '17 at 17:53
  • If you call your code in onload or click event then you can reach your array. @Xufox explanation is right, when run your code that time html element could not be generated but you can see in chrome tools because when you saw it it is already genrated we see evaluted value in console – Ferhat BAŞ Oct 04 '17 at 18:03