TypeError:无法将属性'textContent'设置为null

时间:2019-02-26 00:24:18

标签: javascript html dom-manipulation

当前这段代码有一段时间了,无论我检查多少,我都会不断收到错误。

错误都一样:

TypeError:无法将属性'textContent'设置为null

当我使用querySelector或当我也使用getElementById时。我不知道这是我的HTML还是归咎于它。

让我感到困惑的是,它在这里可以工作...但是当我使用我的VSC(Visual Studio代码)并在chrome上运行该错误时,错误会弹出。是我的代码还是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>

1 个答案:

答案 0 :(得分:0)

您有一些最初调用此函数并获得空值,然后在以后解决的方法。所以试试这个...

var element = document.querySelector("#current-0")
if (element) {
    element.textContent = dice
}