Почему выводится ошибка Uncaught TypeError: Cannot set property 'onclick' of null?

97
17 марта 2021, 11:00

class ToDo{ 
	 
	inputToDo(){ 
		this.list = document.createElement('div'); 
		this.list.className = 'list'; 
		this.creat = document.getElementById('out'); 
		this.creat.append(this.list); 
		this.but = "<li class='li-bottom'><button id='del'>Закрыть</button></li>"; 
		this.result = "<ul><li><h2>" + this.title + "</h2></li>" + "<li>" + this.txt + "</li>" + this.but; 
		this.list.innerHTML = this.result; 
		if(document.getElementById('del').onclick){ 
			alert("sdf"); 
		} 
	} 
	 
	checkText(){ 
		this.textCount = 530; 
		this.titlCount = 27; 
		this.title = document.getElementById('titl').value; 
		this.txt = document.getElementById('txt').value; 
		 
		if(this.title.length <= this.titlCount && !this.title.length == 0){ 
			if(this.txt.length <= this.textCount && !this.txt.length == 0){ 
				this.inputToDo(); 
			}else{ 
				alert('Задача не должена превышать ' + this.textCount + ' символов и не должен ровняться нулю'); 
			} 
		}else{ 
			alert('Заголовок не должен превышать ' + this.titlCount + ' символов и не должен ровняться нулю'); 
		} 
	} 
	 
	deletToDo(){ 
		this.list.remove(); 
	} 
} 
 
window.onload = function(){ 
	var todo = new ToDo(); 
	 
	document.getElementById('push').onclick = function(){ 
		todo.checkText(); 
	} 
	 
	document.getElementById('del').onclick = function(){ 
		todo.deletToDo(); 
	} 
}
html, 
body{ 
	padding: 0; 
	margin: 0; 
	background-color: #15502f; 
} 
 
header{ 
	display: flex; 
	justify-content: center; 
	border-bottom: 1px solid black; 
} 
 
header h1{ 
	color: white; 
	text-shadow: 0 4px 3px black; 
} 
 
main{ 
	display: flex; 
	flex-wrap: wrap; 
	justify-content: center; 
} 
 
.inp{ 
	padding: 30px; 
	width: 100%; 
	display: flex; 
	justify-content: center; 
	border-bottom: 1px solid gray; 
} 
 
.inp form{ 
	width: 303px; 
	display: flex; 
	flex-wrap: wrap; 
	justify-content: center; 
} 
 
.inp textarea{ 
	resize: none; 
    text-align: center; 
} 
 
form input{ 
	margin: 20px; 
	text-align: center; 
} 
 
.out{ 
	width: 100%; 
	display: flex; 
	justify-content: center; 
	flex-wrap: wrap; 
} 
 
.list{ 
	width: 300px; 
	height: 400px; 
	background-color: white; 
	margin: 25px; 
	box-shadow: 0 5px 10px black; 
} 
 
 
.list:hover{ 
	box-shadow: 0 0 25px black; 
	transition: all .1s ease-in; 
} 
 
ul{ 
	list-style: none; 
	padding: 0; 
	margin-top: 0; 
} 
 
.list li{ 
	text-align: center; 
} 
 
.li-bottom{ 
	border-top: 1px solid black; 
	display: flex; 
	justify-content: center; 
	padding-top: 15px; 
} 
 
li:nth-child(1){ 
	height: 27px; 
	margin-top: 10px; 
	margin-bottom: 10px; 
} 
li:nth-child(2){ 
	height: 288px; 
}
<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="utf-8"> 
    <title>ToDo</title> 
    <link rel="stylesheet" href="style.css" type="text/css"> 
  </head> 
  <body> 
    <header> 
      <h1>ToDo List</h1> 
    </header> 
    <main> 
      <section class="inp"> 
        <form method="#" action="#"> 
          <input placeholder="Заголовок" type="text" id="titl"> 
          <textarea rows="10" cols="40" placeholder="Задача" id="txt"></textarea> 
          <input value="Добавить" type="submit" id="push"> 
        </form> 
      </section> 
      <section class="out" id="out"> 
         
      </section> 
    </main> 
    <script src="script.js"></script> 
  </body> 
</html>

Answer 1

Элемент с id='del' создается при каждом вызове метода inputToDo.

В приведенном коде указанный метод нигде не вызывается, следовательно в любой момент времени document.getElementById('del') будет возвращать null.

Answer 2

В момент вызова

document.getElementById('del').onclick = function(){
    todo.deletToDo();
}

элемента[ов] с id='del' не существует. Не говоря уже о том, что Вы их создаете больше одного.

READ ALSO
Как показать элементы при событии React?

Как показать элементы при событии React?

Имеется вот такой React компонент, в который импортирован компонент WorkItem

105
Javascript реализация стрелок в input number - The specified value &ldquo;NaN&rdquo; is not a valid number

Javascript реализация стрелок в input number - The specified value “NaN” is not a valid number

У меня есть корзина товаров, в которой может быть множество различных сущностейИ я пытаюсь реализовать изменения кол-во товара с помощью...

108
(x &lt;= 100) тоже самое что и !(x &gt; 100)?

(x <= 100) тоже самое что и !(x > 100)?

На learnjs в тестах был такой вопросик:

71
~ что значит этот символ в javascript?

~ что значит этот символ в javascript?

Что значит данный символ ~ в этом поле?

111