Avatar of MJ
Flag for United States of America asked on

javascript document.getElementsByClassName returns 0 for length

I have the below function:
    function _dtmIsAppDeclined(){
        var appDeclined = 0;
         //May have to move this into lower if statement 
        if((document.cookie.indexOf('startStandardOaoFlow=') !== -1)){
            s.events += (s.events == '') ? "event33" : ",event33";
        var myCollection = document.getElementsByClassName('region-done-group');
        var i = myCollection.length;
        console.log("myCollection.length: " + i + " <---===> OAO4 myCollection holds: ",myCollection);
        while(i--) {
            if (myCollection[i].innerText.search('we cannot open the account') > -1) {
              console.log("5 ---===> OAO4 FOUND DECLINE TEXT");
            appDeclined = 1;
            s.events += (s.events == '') ? "event35" : ",event35";
            s.eVar23 ='decline';
            // Invoke marketing tags
        return appDeclined;

Open in new window

The issue is that
var myCollection = document.getElementsByClassName('region-done-group');

Open in new window

Returns a length of 0 (see line 10 in the code) but still out puts the collection? I read that it is most likely because the getElementsByClassName returns a live collection. the length property of the object is 0 because at that point of time there is no element with that className in the DOM. ***Maybe 1 out 10 times when refreshing the page, the code works as expected*** How do I ensure that the classname is in the DOM before I do anything else? One caveat is this is a Single Page Application but it does have the ability for the user to refresh the page. This image shows the console log from line 10 above: Image showing console log for CollectionThanks!
Web DevelopmentJavaScript* HTML 5

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
David S.

When are you calling your function?  It sounds like you need a DOMContentLoaded or load event listener.

The function is called either on page load (if user refreshes page) or when there is a pushstate change (Standard detection of the Single Page Application).  So my issue is I need to account for either situation in the same piece of code if possible? If I have to choose a single fix, it would be for the push state change but I'd like to address both situations.
Julian Hansen

Both should be catered for on a page load.

What invokes _dtmIsAppDeclined()?

When you say SPA - what framework / library are you using?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck

H Julian,
The app is made by a 3rd party so I'm not sure what framework it is made on? The _dtmAppDeclined() function is invoked within my code within a Direct Call rule injected via a Tag Management system (DTM). I did get this to work by delaying the code for 2 secs. before it runs but I'm assuming there is a much cleaner way to handle this?
Julian Hansen

Are you placing your code inside a document ready block?

The code is invoked after the web app load on a specific route or when the page is reloaded on that specific route. It lives in a rule {piece of code} that loads when the web app loads but then sits there and waits for the specific route. The web app uses ajax to update the content or uses hidden divs etc.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Julian Hansen

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

I just had to delay the script when loaded. Since this script can be called at 2 different times (page refresh if on a specific route or once it hits this route in the SPA).
Julian Hansen

Delaying the script is not a great solution - you want to rather find what event / condition fires to render the elements you are interested in and then fire your code for analysing those elements.