简体   繁体   中英

classList.remove seems to crash

So basically I'm trying to make a transition. Here's the error message Chrome Gives me:

Uncaught TypeError: Cannot read property 'remove' of undefined

function showDefuseContainer(currentPhase){
    var DefuseContainer = document.getElementsByClassName("Defuser");
    if(currentPhase == "defuse" || currentPhase == "over"){
        DefuseContainer.classList.add("show");
    }else{
        DefuseContainer.classList.remove("show");
    }
}

document.getElementsByClassName() - returns a HTMLCollection - an array-like object.

Either use an id:

document.getElementById("DefuserID")

Or the querySelector to get only the first occurrence:

document.querySelector("Defuser")

Or select the first one in the HTMLCollection by it's index like so:

document.getElementsByClassName("Defuser")[0];

okay, so my suggestion is to use DefuseContainer[0] like

// function receiving currentPhase
function showDefuseContainer(currentPhase){
    var DefuseContainer = document.getElementsByClassName("Defuser");
    if(currentPhase == "defuse" || currentPhase == "over"){
        DefuseContainer[0].classList.add("show"); // if currentPhase  is defuse || over then add show class means show the Container
    }else{
        DefuseContainer[0].classList.remove("show"); // else remove the show class and hide the container
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM