Search code examples
typeerroraddeventlisteneruncaught-reference-error

index.js:107 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')


javascript error line

userComment.addEventListener("input", () => {
  publishBtn.disabled = !userComment.value.trim();
});

html where the input is

    <div id="StartComment" class="commentcontainer">
        <div class="head">
            <br><br><br><h1>Post a Comment!</h1>
            <a href="#publish">Click here to scroll down...</a>
        </div>
        <div>
            <span id="Comment">0</span> Comments
        </div>
        <div class="text">
            <p>I will be happy to hear from you!</p>
        </div>
        <div class="comments"></div>
        <div class="commentbox">
            <img src="commenterpng.png" alt="Commenter" id="CommenterStyle">
            <div class="content">
                <h2>Comment as:</h2>
                <input type="text" value="Anonymouse" class="user">
                <div class="commentinput">
                    <input id="input" type="text" placeholder="Enter your comment..." class="usercomment">
                    <div class="buttons">
                        <button type="submit" id="publish" disabled>Publish</button>
                    </div>
                </div>
                <p class="policy">This site is protected by reCAPTCHA and the Google 
                    <a href="#">Privacy Policy</a> and <a href="#">Terms of Service</a> apply.
                </p>
            </div>
        </div>    
    </div>   

I tried to make a comment section and make it so if you havent typed anything into the comment input box, it would be disabled and if you type anything into it, then it turns abled(enabled) and blue with css


Solution

  • As you've mentioned in a comment, .getElementById() looks for an element with the id attribute (id="usercomment"). .getElementById('userComment') will therefore return nothing (null) as you do not use that ID in the HTML you've provided. This leaves you with two choices:

    1. Add the ID to the element you wish
    2. Use another selector

    As you guessed in your comment, yes, .getElementsByClass('usercomment')[0] could work, but remember, that firstly gets a list of all elements with that class and secondly returns the first one -- ordering will matter if you ever add class="usercomment" to another element on the page.