@narem

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

<!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>


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;
}

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();
	}
}
  • Вопрос задан
  • 19276 просмотров
Решения вопроса 2
rockon404
@rockon404
Frontend Developer
К моменту вызова window.onload() в DOM не существует элемента с id 'del'.
Ответ написан
Комментировать
Vlad_IT
@Vlad_IT Куратор тега JavaScript
Front-end разработчик
У вас элемент с id=del создается внутри inputToDo, которая вызывается в checkText, при клике по push. А вы уже в onload хотите использовать элемент del, который еще не создан.
Решением будет добавлять обработку клика непосредственно после создания элемента del, прям в inputToDo. И еще, как я полагаю, inputToDo будет вызываться много раз, а значит, он будет создавать много кнопок с одинаковым id, что нельзя делать, в одном документе не должно быть элементов с одинаковым id.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
IgorPI
@IgorPI
Автору сюда
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
summer Ярославль
от 100 000 до 140 000 ₽
КРАФТТЕК Санкт-Петербург
от 60 000 до 80 000 ₽
19 апр. 2024, в 23:00
5000 руб./за проект
19 апр. 2024, в 20:43
20000 руб./за проект