TypeError: Cannot set property 'textContent' of null

32,268

You have something that is calling this initially and getting a null value and then resolving later i think. So try this...

var element = document.querySelector("#current-0")
if (element) {
    element.textContent = dice
}
Share:
32,268
Evie
Author by

Evie

Updated on February 26, 2020

Comments

  • Evie
    Evie about 4 years

    Currently having issues with this code for a while, and I keep getting errors no matter how much i check it out.

    The errors are all the same:

    TypeError: Cannot set property 'textContent' of null

    when i'm using querySelector or when i'm using getElementById as well. I don't know if it's my HTML or if i'm imputing it wrong.

    what i'm getting confused in is it works here... but the error pops up when i'm using my VSC (visual studio code) and running it on chrome, the error shows up. Is it my code or the VSC?

    var dice = Math.floor(Math.random()* 6) +1;
    
    document.querySelector("#current-0").textContent = dice;
    <div class="wrapper clear-fix">
        <div class="player1-panel active">
            <div class="player-name" id="player-1">Player 1</div>
            <div class="player-score" id="score-1">100</div>
            <div class="player-current-box">
                <div class="player-current-label">Current</div>
                <div class="player-current-score" id="current-0">11</div>
             </div>
        </div>
    
            <div class="player2-panel">
                <div class="player-name" id="player-2">Player 2</div>
                <div class="player-score" id="score-2">00</div>
    
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="currentScore-2">00</div>
                </div>
            </div>
            <button class="btn-rules"><i class="material-icons">
                    help</i>Rules</button>
            <button class="btn-newGame"><i class="material-icons">
                    add_circle_outline
                </i>New Game</button>
            <button class="btn-rollDice"><i class="material-icons">
                    autorenew</i>Roll dice</button>
            <button class="btn-hold"><i class="material-icons">
                    play_for_work</i>Hold</button>
    
            <input type="text" placeholder="Goal" class="finalScore">
            <img src="images/dice5.png" atl="dice" class="dice" id="dice1">
            <img src="images/dice5.png" atl="dice" class="dice" id="dice2">
    
    </div>

  • GregL
    GregL about 5 years
    You're on the right track, but all this code will do if put in the same place as the original code is eliminate the error, not solve the problem. (The if check will fail, and thus not set the textContent correctly).