The error "Uncaught TypeError: input is null" indicates that the script is trying to access an element with the ID 'id', but it cannot find it in the DOM at the time the script runs. This typically happens if the script is executed before the HTML elements are fully loaded.
To fix this issue, you should ensure that your JavaScript runs after the DOM has fully loaded. One common way to do this is to place your script tag at the end of the body section, just before the closing </body> tag. Here’s how to do it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
</head>
<body>
<input type="text" id="id" placeholder="Enter a todo">
<button id="btn">Add Todo</button>
<div id="todos"></div>
<script>
const input = document.getElementById('id');
const btn = document.getElementById('btn');
const todos = document.getElementById('todos');
const addTodo = () => {
var paragraph = document.createElement('p');
paragraph.classList.add('para');
todos.appendChild(paragraph);
paragraph.textContent = input.value;
paragraph.addEventListener('click', () => {
paragraph.style.textDecoration = 'line-through';
paragraph.style.textDecorationColor = 'greenYellow';
})
paragraph.addEventListener('dblclick', () => {
todos.removeChild(paragraph);
})
}
btn.addEventListener('click', addTodo);
</script>
</body>
</html>
Alternatives:
If you want to keep your script in the <head>, you can wrap your JavaScript code in a DOMContentLoaded event listener to ensure it runs only after the DOM is completely loaded:
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('id');
const btn = document.getElementById('btn');
const todos = document.getElementById('todos');
const addTodo = () => {
var paragraph = document.createElement('p');
paragraph.classList.add('para');
todos.appendChild(paragraph);
paragraph.textContent = input.value;
paragraph.addEventListener('click', () => {
paragraph.style.textDecoration = 'line-through';
paragraph.style.textDecorationColor = 'greenYellow';
});
paragraph.addEventListener('dblclick', () => {
todos.removeChild(paragraph);
});
}
btn.addEventListener('click', addTodo);
});
This should resolve your issue. If you have any further questions or need more help, feel free to ask!