@Web_junior

Почему возникает такая ошибка Uncaught TypeError: Cannot set property 'onclick' of null at script.js:4?

Пишу скрипт для добавления комментариев на сайт.
Вот, как это выглядит:
HTML
<form>
                            <div class="form-group">
                              <label for="comment-name">Name:</label>
                              <input type="email" class="form-control" id="comment-name"  placeholder="Enter your name">
                            </div>
                            <div class="form-group">
                              <label for="comment-body">Comment:</label>
                              <textarea type="password" class="form-control" id="comment-body" placeholder="comment"></textarea>
                            </div>
                            <div class="form-group form-check text-right">
                                    <button type="submit" id="comment-add" class="btn btn-primary">add Comment</button>
                            </div>
                          </form>

Вот JS:
let comments = [];


document.getElementById('comment-add').onclick = function(){
	event.preventDefault()
    let commentName = document.getElementById('comment-name');
    let commentBody = document.getElementById('comment-body');

    let comment = {
        name : commentName.value,
        body : commentBody.value,
        time : Math.floor(Date.now() / 1000)
    }

    console.log(comment);
}


Возникает ошибка:
script.js:4 Uncaught TypeError: Cannot set property 'onclick' of null
at script.js:4

Из-за чего она вообще может возникать?
  • Вопрос задан
  • 5692 просмотра
Решения вопроса 1
Rsa97
@Rsa97
Для правильного вопроса надо знать половину ответа
На момент выполнения скрипта в DOM отсутствует элемент с id='comment-add'.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы