Understanding the Values Obtained in document.getElementsByClassName

Asked 2 years ago, Updated 2 years ago, 107 views

When you retrieve a specific class in document.getElementsByClassName and loop it in forEach, only one element that should have two counts.

If you check the console, you will receive the following values.
MODAL.methods.show()=length:2
MODAL.methods.overlay()=length:2
MODAL.methods.close()=length:1

QuerySelectorAll solves this problem, but I don't know why getElementsByClassName doesn't work...

If anyone knows the cause, please let me know <(__)>

MODAL.methods={
    show:function(elm){
        var$self=elm;
        var$next=$self.nextElementSibling;
        if($next.classList.contains(MODAL.tar)&!$self.classList.contains(MODAL.active)){
            $self.classList.add(MODAL.active);
            $next.classList.add(MODAL.active);

            $next.style.display='block';

            console.log( document.getElementsByClassName(MODAL.active));

            MODAL.methods.overlay();
        }
    },
    close:function(){
        var$close= document.getElementById(MODAL.close);
        console.log( document.getElementsByClassName(MODAL.active));
        Array.prototype.forEach.call( document.getElementsByClassName(MODAL.active), function(elm){
            elm.classList.remove(MODAL.active);
            if(elm.classList.contains(MODAL.tar)){
                elm.style.display='none';
            }
        });
        $close.remove();
    },
    overlay:function(){
        console.log( document.getElementsByClassName(MODAL.active));
        document.body.insertAdjacentHTML('beforeend','<divid="'+MODAL.close+'" class="modal-overlay" onClick="MODAL.methods.close();">span class="modal-overlay_child;>>>>dividan"modal-overlay_>>>>>lt;slide;>>>>>
    }
};

javascript html css

2022-09-30 21:32

1 Answers

The reason was that HTMLCollection was dynamically referring to the class.
GetElementsByClassName will return HTMLCollection, so
"By changing the static NodeList to ""querySelectorAll"" that returns it return!"

I have left a note on Qita.
https://qiita.com/o-sushi/items/929f9bbf46d4f61819ac


2022-09-30 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.