JavaScript will not change display to "none"

Issue

I am trying to add a click event handler to a button that will cause it to change the CSS display property of a sign-in form to ‘none’.

The JS:

// make the form disappear when the user clicks initSignUpBtn
const initSignUpBtn = document.querySelector(".btn signup-btn");
initSignUpBtn.addEventListener("click", () =>{
    document.getElementById("signinForm").style.display="none";
});

The HTML:

<form class="signin-form" id="signinForm">
    <div class="form-group">
        <input type="email" class="email-input" id="emailInput" placeholder="Email or username">
    </div>
    <div class="form-group">
        <input type="password" class="pass-input" id="passwordInput" placeholder="Password">
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input class="form-check-input" type="checkbox"> Remember me<a class="need-help" href="#">Need Help?</a>
        </label>
    </div>
    <button type="button" class="btn signin-btn" id="signinbtn">Sign in</button>
    <button type="button" class="btn signup-btn" id="initSignUpBtn">New? Sign up!</button>

</form>

I added an event listener of type ‘click’ to the button, and wrote an anonymous function that changes the display property of the form to ‘none’ but this did not work.

Solution

Your querySelector is incorrect. Why not use document.getElementById("initSignUpBtn") since you have an ID on it? If you do want to use querySelector, it should be document.querySelector(".btn.signup-btn") or document.querySelector(".signup-btn").

Answered By – Zac Anger

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published