简体   繁体   中英

Cannot solve Uncaught TypeError: Cannot read property 'classList' of null

I am trying to hide the accountSlider div on the press of a button. However, When I press the button I get: Uncaught TypeError: Cannot read property 'classList' of null

How could I fix this?

Here is my Code

<style>

    .hideSlider {
        transform: translateX(-110%);
    }
</style>
<script>

    const accountSlider = document.getElementById("accountSlider");
    const imageX = document.getElementById("imageX");

    function hideSlider() {
        accountSlider.classList.add("hideSlider");
    }

</script>

<div class="accountSlider">
    <button id="closeButton" onclick="hideSlider()">
        <img src="@/assets/closeX.png" width="30" class="buttonImg" id="imageX" />
    </button>
</div>

Thanks for every help!

Your html attribute is class not id. Changes it ti this

<div id="accountSlider">
    <button id="closeButton" onclick="hideSlider()">
        <img src="@/assets/closeX.png" width="30" class="buttonImg" id="imageX" />
    </button>
</div>

or use querySelector(".accountSlider")

getElementById() method take ID name as argument not class name.

 const accountSlider = document.getElementsByClassName("accountSlider")[0];/*or use document.querySelector(".accountSlider");*/ const imageX = document.getElementById("imageX"); function hideSlider() { accountSlider.classList.add("hideSlider"); }
 .hideSlider { transform: translateX(-110%); }
 <div class="accountSlider"> <button id="closeButton" onclick="hideSlider()"> <img src="@/assets/closeX.png" alt = 'a unknown image' width="30" class="buttonImg" id="imageX" /> </button> </div>

It's pretty simple: if you define the DOM nodes you are trying to retrieve synchronously in the script that is executed before these DOM nodes are even created, the methods will return undefined, as nothing is live yet.

If you move your selectors within the global function you are defining (a bad practice, yet allowed), you won't have issues.

function hideSlider() {
    const accountSlider = document.querySelector(".accountSlider");
    accountSlider.classList.add("hideSlider");
}

That's it.

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