LoginSignup
3
1

More than 5 years have passed since last update.

document.getElementsByClassNameでうまく取得できない…

Last updated at Posted at 2018-07-31

初投稿!!

document.getElementsByClassNameで特定のclassを取得して、forEachでループさせる際に、2つあるはずの要素が1つしかカウントされない…

script.js
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', '<div id="' + MODAL.close + '" class="modal-overlay" onClick="MODAL.methods.close();"><span class="modal-overlay_child">close</span></div>');
    }
};

MODAL.methods.show()だとlength: 2
MODAL.methods.overlay()だとlength: 2
なのに…
MODAL.methods.close()だとlength: 1

querySelectorAllで対応すると解決するのだが、getElementsByClassNameだとうまくいかない理由がわからないので気持ち悪い( ^ω^)・・・

理由がわかる方いらっしゃいましたらご教授ください<(_ _)>

3
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1