Avatar of MJ
MJFlag 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
            _dtmInsertStaticTags(sTags3);
            }
        }
        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: User generated imageThanks!
Web DevelopmentJavaScript* HTML 5

Avatar of undefined
Last Comment
Julian Hansen
Avatar of David S.
David S.
Flag of United States of America image

When are you calling your function?  It sounds like you need a DOMContentLoaded or load event listener.
Avatar of MJ
MJ
Flag of United States of America image

ASKER

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.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Both should be catered for on a page load.

What invokes _dtmIsAppDeclined()?

When you say SPA - what framework / library are you using?
Avatar of MJ
MJ
Flag of United States of America image

ASKER

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?
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Are you placing your code inside a document ready block?
Avatar of MJ
MJ
Flag of United States of America image

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of MJ
MJ
Flag of United States of America image

ASKER

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).
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

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.
JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo