cannot set property onclick of null

I am creating an HTML page, Which is built using bootstrap. Here is the final HTML code and code of hello.js file:

When I click on the button using submit then instead of alert I am getting error

Uncaught TypeError: Cannot set property ‘onclick’ of null

Can anyone please tell me why I am facing this error?? Help to resolve it.

5 Answers 5

The problem seems to be you are executing the script before the element is loaded.

I assume this script is added in the hello.js file which is added before the DOM is created.

The solution here is to execute the script after the DOM is ready like:

All JavaScript code which deals with DOM elements like the one above has to be executed only after the DOM is loaded.

This question already has an answer here:

I’m having problems making my window alert pop up with a simple checkbox and can’t for the life of me figure out why. Here’s the basic Javascript and HTML:

Which throws: Uncaught TypeError: Cannot set property ‘onclick’ of null under

Are there any visible reasons for this error in my code?

onLoad срабатывает всего один раз.
Вы ожидаете, что события будут зарегистрированы на все элементы которые вы создаёте, но это не так.

Вы же не используете JQuery, вы не делегируете события.

Поэтому нужно события каждый раз регистрировать.

Либо, повесить обработчик на родителя, и смотреть таргет

load – страница и все ресурсы загружены, используется редко, обычно нет нужды ждать этого момента.

Когда Вы открыл страницу в браузере, происходит событие load.
Оно происходит всего один раз.

narem, Тыкать можно много раз, а событие происходит всего один раз.

Многое зависит от того, что вы инициализировали в этот момент.
В вашем случае вы пытаетесь повесить все события (это вы так думаете)

Не забывайте DOM это иерархия.

Если повесить событие на Element1
то li Element1 li и будет реагировать на событие.

Если-же повесить на ul то реагировать будут все дочерние элементы и ul включительно.

Отсюда вывод:
Незачем вешать на каждый элемент события!
Повесьте на ul

И когда начнете кликать по li в обработчике произойдёт событие.
target поможет понять где оно произошло.

Оцените статью